Как отсортировать общий c объект LinkedList по именам полей - PullRequest
0 голосов
/ 12 июля 2020

У меня есть 4 класса Car, GenericCar, Utility и мой основной класс. Мне нужно хранить информацию об автомобилях с тремя полями: имя, цена и производство в общем c связанном списке. Я застрял в том, как отсортировать их по название поля, например, по названию или по цене. Мне нужна помощь в решении этой проблемы. вот код: class Car

public class Car {
String name;
Double price;
String production;

public Car() {
}

public Car(String name, Double price, String production) {
    this.name = name;
    this.price = price;
    this.production = production;
}

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 getProduction() {
    return production;
}

public void setProduction(String production) {
    this.production = production;
}

@Override
public String toString() {
    return name+" "+price+" "+production; //To change body of generated methods, choose Tools | Templates.
}
}

My genericCar class

class GenericCar
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;


public class GenericCar<T> {

private LinkedList<T> items = new LinkedList<T>();

public LinkedList<T> getItems() {
    return items;
}

public void setItems(LinkedList<T> items) {
    this.items = items;
}
private T t;

public GenericCar() {
}

public GenericCar(T t) {
    this.t = t;
}

public T getT() {
    return t;
}

public void setT(T t) {
    this.t = t;
}
public void add(T item){
    items.addFirst(item);
}
public void display(){
    for (T item : items) {
        System.out.println(item+" ");
    }
}
public int getsize(){
    return items.size();
}
public boolean checkEmpty(){
    return items.isEmpty();
}
public void delete(int pos){
     items.remove(pos);
     display();
}
public static int stringCompare(String str1, String str2) 
{ 

    int l1 = str1.length(); 
    int l2 = str2.length(); 
    int lmin = Math.min(l1, l2); 

    for (int i = 0; i < lmin; i++) { 
        int str1_ch = (int)str1.charAt(i); 
        int str2_ch = (int)str2.charAt(i); 

        if (str1_ch != str2_ch) { 
            return str1_ch - str2_ch; 
        } 
    } 

    // Edge case for strings like 
    // String 1="Geeks" and String 2="Geeksforgeeks" 
    if (l1 != l2) { 
        return l1 - l2; 
    } 

    // If none of the above conditions is true, 
    // it implies both the strings are equal 
    else { 
        return 0; 
    } 
}

}

class Утилита для проверки ввода

public class Utility {
    static Double getDouble(String mesg,Double max, Double min){

    Double val=0.0;
    int check=0;
    Scanner sc=new Scanner(System.in);
    while(true){
        System.out.print(mesg);
        try {
            val=Double.parseDouble(sc.nextLine());
            if(val>=min&&val<=max){
                check=1;
                break;
            }
            else{
                System.out.println("Enter again!");
            }
        } catch (Exception e) {
            System.out.println("sorry,Enter again");
        }
        if(check==1){
            break;
        }
    }
    return val;
}
static int getint(String mesg,int max, int min){
    
    int val=0;
    int check=0;
    Scanner sc=new Scanner(System.in);
    while(true){
        System.out.print(mesg);
        try {
            val=Integer.parseInt(sc.nextLine());
            if(val>=min&&val<=max){
                check=1;
                break;
            }
            else{
                System.out.println("Enter again!");
            }
        } catch (Exception e) {
            System.out.println("sorry,Enter again");
        }
        if(check==1){
            break;
        }
    }
    return val;
}
static String getString(String mesg,boolean IsEmpty){
    
    String str;
    Scanner sc=new Scanner(System.in);
    if(IsEmpty){
        System.out.print(mesg);
        str=sc.nextLine();
    }
    else{
        while(true){
            System.out.print(mesg);
            str=sc.nextLine();
            if(str.isEmpty()){
                System.out.println("Enter again,pls");
            }else{
                break;
            }
        }
    }
   return str;
}
static boolean getIsYOrN(String mesg){
    String str;
    Scanner sc=new Scanner(System.in);
    while(true){
        System.out.println(mesg);
        str=sc.nextLine();
        if(str.equalsIgnoreCase("y")){
            return true;
        }
        else if(str.equalsIgnoreCase("n")){
            return false;
        }
    }
}
}

и мой основной класс

    public static void main(String[] args) {
    // TODO code application logic here
    GenericCar<Car> carList=new GenericCar<>();
    String name;
    Double price;
    String production;
    Utility utility=new Utility();
    Scanner sc=new Scanner(System.in);
    int userChoice=0;
    int pos=0;
     do{ 
         
         System.out.println("--------------------------------");
         System.out.println("1.add");
         System.out.println("2.Display");
         System.out.println("3.getSize");
         System.out.println("4.CheckEmpty");
         System.out.println("5.Delete");
         System.out.println("6.sort by name");
         userChoice=utility.getint("enter choice:",6,1);
        switch(userChoice){
            case 1: name=utility.getString("1.Enter name:",false); 
            price=utility.getDouble("Enter price:",30000.0,0.0);
            production=utility.getString("Enter production:",false);
            Car c=new Car(name, price, name);carList.add(c);
            break;
            case 3: System.out.println("3.size:"+carList.getsize());break;
            case 2:carList.display();break;
            case 4: System.out.println("4.CheckEmpty:"+carList.checkEmpty());break;
            case 5: utility.getint("5.delete at 
``position:",carList.getsize(),1);carList.delete(pos);break;
            case 6: System.out.println("sort by name:");
            ;break;
            default:System.exit(0);break;
        }
    }while(true);
}
}

1 Ответ

0 голосов
/ 12 июля 2020

Я бы рекомендовал построить карту желаемого поля к объекту, чтобы

0: Field -> Car
1: Field -> Car
...

Затем вы можете просто отсортировать карту по желаемым параметрам, и автомобили будут отсортированы рядом с ними

...