Reputation: 3
I am working on a Java program that is making an array of colors that have been used in another array to draw a picture. I am stumbling on writing code that creates this new array, while also excluding colors that have been added to this array already.
I would appreciate any help into where I am going wrong with my code.
Thanks. My code is below:
public ArrayList<Color> getColorList()
{
ArrayList<Color> getColorList;
getColorList = new ArrayList<Color>();
int index = 0;
boolean colorAdded = false;
for(Stroke stroke : drawing){
while(index <= getColorList.size() && colorAdded == false) {
if(getColorList.get(index) == stroke.getColor()){
colorAdded = true;
}
else{
index = index + 1;
}
}
if(colorAdded == false){
getColorList.add(stroke.getColor());
}
index = 0;
colorAdded = false;
}
return getColorList();
}
Upvotes: 0
Views: 301
Reputation: 7940
Store the colors in a Set and you dont need to worry about duplication:
Set<Color> distinctColors = new HashSet<Color>();
distinctColors .add(stroke.getColor());
return new ArrayList<Color>(distinctColors );
Above code will return an arraylist of distinct colors.
EDIT[After comments]:
Color class should implement hashcode and equals methods such that if 2 objects are equal then they have same hashcode and if 2 objects have same hashcode then they may or may not be equal.
Upvotes: 1