I wanted to do a task related to Java collections. Decided to use ArrayList. But I ran into a number of problems:
when added to the collection writes
cannot find symbol method ToyBlocks
And when you try to compare objects through the comparator, you swear at the error:
int cannot be deferenced
Tell me, what are the errors and how to fix it?
import java.util.ArrayList; import java.util.Comparator; class ToyBlocks { String name; int amount; int uah; int kopeck; ToyBlocks(String name, int amount,int uah, int kopeck) { this.name = name; this.amount = amount; this.uah = uah; this.kopeck = kopeck; } } class ToyBlocksComparator implements Comparator { @Override public int compare(Object toyblocks1, Object toyblocks2) { return ((ToyBlocks) toyblocks1).uah.compareTo(((ToyBlocks) toyblocks2).uah);//int cannot be deferenced } } public class SortBlocks { public static void main(String[] args) { ArrayList<ToyBlocks> blocks = new ArrayList(6); blocks.add(ToyBlocks("первый набор", 18, 18, 0));// cannot find symbol method ToyBlocks blocks.add(ToyBlocks("Второй набор", 12, 12, 0)); blocks.trimToSize(); Collections.sort(blocks, new ToyBlocksComparator()); } }
newYou needblocks.add(new ToyBlocks......and yet you need to write a sheet:ArrayList<ToyBlocks> blocks = new ArrayList<ToyBlocks>(6);orArrayList<ToyBlocks> blocks = new ArrayList<>(6);in the 7+ version - Alexey ShimanskycompareTomethod on the primitive typeint, which is contained intoyblocks1.uah... and it (the compareTo method) can only be called on reference types ... on objects, krch)) ...... as as a consequence, you need to organizereturnsimple way, i.e. return -1, 0 or 1, comparing the numbers for more less ... or usereturn Integer.compare(одно число, второе число)- Alexey ShimanskycompareuseObject, and notToyBlocksas the type of the input parameter? - Alexey Shimansky