Hey there ! Here is my question:
I am facing with an easy problem i think. I am creating 4 objects. Then i make an ArrayList in which i am storing the 4 objects. The excercise is to delete the objects that are the same(equals) and then sort them by smaller to bigger . Comparison is being made by it's objects price.
Here is the code:
main:
public class Application {
public static void main(String[] args) {
Product p = new Product(15,"test",3.45);
Product p2 = new Product(15,"test",3.45);
Product p3 = new Product(4716,"koukouroukou",1.25);
Product p4 = new Product(6002,"bananofatsoula",0.60);
ProductDatabase productDatabase = new ProductDatabase();
productDatabase.addProduct(p);
productDatabase.addProduct(p2);
productDatabase.addProduct(p3);
productDatabase.addProduct(p4);
productDatabase.printDatabase();
System.out.println("\n\n");
System.out.println("After deleting Equals:\n");
productDatabase.deleteEquals();
productDatabase.printDatabase();
System.out.println("\n\n");
productDatabase.sortDatabase();
productDatabase.printDatabase();
}
}
Product:
public class Product {
private int code;
private String name;
private double price;
public Product(int code, String name, double price){
this.code = code;
this.name = name;
this.price = price;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString(){
return code+" , description: "+name+", price: "+price;
}
public int hashCode(){
return 31 * code + name.hashCode();
}
public boolean equals(Object o){
Product other = (Product)o;
return (this == other);
}
}
ProductDatabase:
import java.util.ArrayList;
import java.util.Collections;
public class ProductDatabase {
private ArrayList<Product> productDatabase;
public ProductDatabase(){
this.productDatabase = new ArrayList<Product>();
}
public void addProduct(Product p){
if(!this.productDatabase.contains(p)){
this.productDatabase.add(p);
}
}
public void printDatabase(){
for(Product product : this.productDatabase){
System.out.println(product);
}
}
public void deleteEquals(){
for(int i=0;i<productDatabase.size()-1;i++){
if(productDatabase.get(i).equals(productDatabase.get(i++)))
productDatabase.remove(i);
}
}
//Ταξινόμηση της Λίστας κατά αύξουσα τιμή!
public void sortDatabase(){
for(int j=0;j<productDatabase.size()-1;j++){
for(int i =0;i<productDatabase.size()-j-1;i++){
if(compareTo(i)){
Collections.swap(productDatabase,i,i++ ); //Με την Χρήση της Collections βιβλιοθήκης κάνω SWAP! Πρέπει να βάλω την βιβλιοθήκη όμως!
}
}
}
}
public boolean compareTo(int index){
if(productDatabase.get(index).getPrice() > productDatabase.get(index++).getPrice()){
return true;
}
else
return false;
}
}
Thanks in advance guys!