packagetemplate7; importjava.util.*; public classTemplatesMain { /** * @param ar
ID: 3618569 • Letter: P
Question
packagetemplate7;
importjava.util.*;
public classTemplatesMain
{
/**
* @param args the command linearguments
*/
public static void main(String[] args)
{
ArrayList<Product>pl2 = new ArrayList<Product>();
pl2.add(new Product(1,"P1"));
pl2.add(new Product(2,"P2"));
pl2.add(new Product(4,"Kingdom"));
pl2.add(new Product(1,"P1"));
sort(pl2);
//ArrayList<Product> pl1 = newArrayList<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 void sort(List<T> list)
{
int j;
for(int i = 0; i < list.size()-1;i++)
{
int smallest = i;
for(j = i+1; j < list.size(); j++)
{
if(list.get(j).compareTo(list.get(smallest))<0)
{
smallest = j;
}
}
if(i != j)
{
T temp = list.get(smallest);
list.set(smallest, list.get(j));
list.set(j, temp);
}
}
}
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(((Product)o).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
if(i != j) { T temp = list.get(smallest); list.set(smallest, list.get(j)); list.set(j, temp); } this part is having the problem in that code. Change this code tothe following if(i != j) { T temp = list.get(smallest); list.set(smallest, list.get(i); list.set(i, temp); } Let me know, if you need the complete working code..
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.