0

When I attempt to add to my array list (stringer), this error occurs:

error: no suitable method found for add(Fish)
      stringer.add(f);

In this code:

public class Habitat {

ArrayList<String> stringer = new ArrayList<String>();
int[] fishArr;
public int maxCount=25; 
public int minCount=9; 
public int maxWeight=10; 
public int minWeight=1; 
public int catchProbability=30; //0.3 

public int[] stockUp(){
  int numofF = minCount + (int)(Math.random() * ((maxCount - minCount) + 1));
  for(int i = 0; i<numofF; i++){
     fishArr[i] = minWeight + (int)(Math.random() * ((maxWeight - minWeight) + 1));
  }
  return fishArr;
}


public Habitat(){
  int[] hab;
}

public void addFish(Fish f) {
  stringer.add(f);
}

public void removeFish(Fish f){
  stringer.remove(f);
}

public void printFish(){
  System.out.println(stringer);
}
}

The remove works just fine, so I don't understand why the add doesn't work. I would like the problem explained, so I don't make the same mistake again.

1
  • 5
    ArrayList<String>........................ Commented Feb 24, 2014 at 2:44

2 Answers 2

4

You've declared the List so that it is expecting String values only, but you are trying to add Fish object to it...

This is a violation of the contract you made with ArrayList

Try using ArrayList<Fish> stringer = new ArrayList<Fish>(); instead

Take a look at Generics for more details

Sign up to request clarification or add additional context in comments.

2 Comments

As op mention remove work fine. He may doing something wrong. Is it so?
@NFE List#remove accepts an Object parameter and therefore isn't part of the generics contract. The code won't "work", as it won't compile
0

stringer is ArrayList of String you cannot add Objects of type Fish to it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.