packagetemplate; importjava.util.*; public classtemplates6Main { /** * @param ar
ID: 3618567 • Letter: P
Question
packagetemplate;
importjava.util.*;
public classtemplates6Main
{
/**
* @param args the command linearguments
*/
public static void main(String[] args)
{
// System.out.println( min(newProduct(4, "de"), new Product(3, "bc")));
ArrayList<Product> pl2 = newArrayList<Product>();
pl2.add(new Product(1,"P1"));
pl2.add(new Product(2,"C2"));
pl2.add(new Product(4,"Kingdom"));
pl2.add(new Product(1,"B1"));
System.out.println(sort(pl2));
ArrayList<Product>pl1 = new ArrayList<Product>();
pl1.add(new Product(1,"P1"));
pl1.add(new Product(2,"P2"));
pl1.add(new Product(4,"Kingdom"));
pl1.add(new Product(1,"P1"));
System.out.println(duplicate(pl1));
}
public static < T extends Comparable > Tsort(List<T> col)
{
int count;
for(T i1 : col)
{
count= 0;
for(Ti2 : col)
{
if(i1.compareTo(i2) < 0)
count++;
}
if(count > 1)
return true;
}
return false;
}
public static < T > booleanduplicate(List< T > coll)
{
int count;
for(T i1 : coll)
{
count= 0;
for(Ti2 : coll)
{
/**
* it compares references so equals() has been defined in productclass
*/
if(i1.equals(i2))
count++;
}
if(count > 1)
return true;
}
return false;
}
}
class Product implements Comparable
{
private int id;
private String name;
publicProduct(int i, String n)
{
name = n;
id = i;
}
public void display()
{
System.out.println(id +"" +name);
}
public String toString()
{
return id+" "+name;
}
public int compareTo(Object o)
{
returnname.compareTo(name);
}
public boolean equals(Object obj)
{
Product p2 =(Product)obj;
returnname.equals(p2.name);
}
public int hashCode()
{
int hash = 5;
hash = 11*hash+id;
hash = 11*hash +(name !=null ? name.hashCode(): 0);
return hash;
}
}
Explanation / Answer
YourcompareTo() iscurrently: public int compareTo(Objecto) { returnname.compareTo(name); } It should be: public intcompareTo(Object o) { returnname.compareTo(((Product)o).name); } I'm also not sure what your sort() method is doing, because I don't see anyswaps. public staticvoid sort(Listlist) { for(int i = 0; iRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.