简体   繁体   English

在Java中排序对象数组

[英]sorting an array of objects in java

I'm trying to make a java application that's allows the user to make a catalog for a supermarket, and then display all the products that the user entered to the catalog in ascending order according to the code entered by the user.I have searched for it and found that I can use a method called "sort",but the problem I tried to implement it but it doesn't work with me ,and I don't know where to put it in my code . 我正在尝试制作一个Java应用程序,该应用程序允许用户创建超市的目录,然后根据用户输入的代码以升序显示用户输入到目录中的所有产品。它发现我可以使用一种称为“ sort”的方法,但是我尝试实现该问题,但是它对我不起作用,并且我不知道将其放在代码中的位置。

The code that I wrote : 2 classes class 1: 我写的代码:2类,类1:

public class Catalog {

private String description ; 
private String code ;
private double price ;
private String phrase ;

int counter = 0;

private Catalog [] list = new Catalog [100];

public Catalog (String productDescription , String productCode , double    productPrice  , String productPhrase)
{
    description = productDescription;
    code = productCode;
    price = productPrice;
    phrase = productPhrase;
}

public void setDescription (String productDescription)
{
    description = productDescription;
}

public String getDescription ()
{
    return description;
}

public void setCode (String productCode)
{
    code = productCode;
}

public String getCode ()
{
    return code;
}

public void setPrice (double productPrice)
{
    price = productPrice;
 }

public double getPrice ()
{
    return price;
 }

public void setPhrase (String productPhrase)
{
    phrase = productPhrase;
}

public String getPhrase ()
{
    return phrase;
}

class 2: 第2类:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CatalogTest {
    public static void main(String[] args) throws IOException {
        String name = null;
        String code = null;
        double price = 0.0;
        String phrase = null;
        BufferedReader input = new BufferedReader (new InputStreamReader  (System.in));
        Catalog product = new Catalog(name,code,price,phrase);
        Catalog [] productsArray = new Catalog [100];

        for (int i = 0 ; i < productsArray.length ; i ++)
        {
            System.out.println("Enter product description (or # to stop): ");
            name = input.readLine();
            if (!("#".equals(name)))
            {
                productsArray [i] = product;
                product.setDescription(name);
                System.out.println("Enter product code: ");
                code = input.readLine();
                productsArray [i] = product;
                product.setCode(code);
                System.out.println("Enter product unit price: ");
                price = Double.parseDouble(input.readLine());
                productsArray [i] = product;
                product.setPrice(price);
                System.out.println("Enter product unit phrase: ");
                phrase = input.readLine();
                productsArray [i] = product;
                product.setPhrase(phrase);
                productsArray [i] = new Catalog (name,code,price,phrase);
            }
            else
            {
                System.out.println("Your Catalog:");
                for (int j = 0; j < productsArray.length; j++)
                {
                    if(productsArray[j]!=null)
                    {
                        System.out.printf("%s, %s,$%.2f %s,",
                        productsArray[j].getCode(),
                        productsArray[j].getDescription(),
                        productsArray[j].getPrice(),
                        productsArray[j].getPhrase());
                        System.out.println();
                    }
                }
                break;
            }
        }
    }
}

So any help PLEASE ?? 有什么帮助吗?

You can write your own Comparator then call the Arrays.sort method: 您可以编写自己的Comparator,然后调用Arrays.sort方法:

public static class MyComparator implements Comparator<Catalog> {
    @Override
    public int compare( Catalog first, Catalog second ) {
        return first.getCode().compareTo( second.getCode() );
    }        
}

Arrays.sort( productsArray, new MyComparator() );

Some things first: 首先要注意的是:

private Catalog [] list = new Catalog [100];

Your Catalog class is actualy a single product in the catalog, while the Catalog[] array you instantiate is the catalog itself. 您的Catalog类实际上是Catalog的单个产品,而您实例化的Catalog[]数组是目录本身。

There are many options you can take. 您可以采取多种选择。 I suggest you use a list instead of an array if you can. 我建议您尽可能使用列表而不是数组。 You can either use Collections#sort and make your Catalog ( Product from now on) class implement the Comparable interface. 您可以使用Collections#sort并使您的Catalog (从现在开始为Product )类实现Comparable接口。 There, override the compareTo method and do the comparation based on the code. 在那里,重写compareTo方法并根据代码进行比较。

Other alternative is to use a TreeSet and defining the Comparator that will be used as a base for the sorting. 其他替代方法是使用TreeSet并定义将用作排序基础的Comparator I think you'll be just fine with the first option. 我认为第一种选择会很好。

On the other hand, if you have to stick to an array makke use of a Comparator (like with the TreeSet ) and the Arrays#sort method. 另一方面,如果必须坚持使用Comparator (如TreeSet )和Arrays#sort方法,则可以使用Arrays#sort

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM