user2877117
user2877117

Reputation:

Adding to an Array List

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.

Upvotes: 0

Views: 65

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347204

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

Upvotes: 4

Kakarot
Kakarot

Reputation: 4252

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

Upvotes: 0

Related Questions