Java将新对象添加到TreeSet并对其进行排序

时间:2015-05-24 11:19:47

标签: java sorting comparator treeset

我无法弄清楚我试图制作的某个程序存在的问题。它是关于从文件中获取信息,对数据进行排序以及将新排序的数据存储到另一个文件中。但是因为我还是Java的新手,我在使用几个函数和方法时遇到了一些麻烦。所以这就是我到目前为止所做的:

Public Class Planina:

public abstract class Planina {

   protected String mName;
   protected String Country;
    public Planina(String mname, String country) 
    { 
        mName = mname;
        Country = country;
    } 
    public Planina() 
    { 
        mName = "Name";
        Country = "Country";
    } 
    public void setmName(String mname) 
    { 
        mName = mname; 
    } 
    public String getmName() 
    { 
        return mName; 
    }

    public void setCountry(String country){

        Country = country;
    }

    public String getCountry(){

        return Country;
    }
    public String toString() 
    { 
        return "Mountain name: " + mName + "; Country: " + Country; 
    } 
}

Public Class Vrah延伸Planina:

public class Vrah extends Planina implements Comparable<Vrah> {

private String pName; 
private int Height; 
public Vrah(String mname, String country, String pname, int height) 
{ 
    super(mname, country); 
    pName=pname; 
    Height=height; 
    if(height<0) 
        throw new IllegalArgumentException("Height cannot be negative!"); 
} 
public Vrah() 
{ 
    super("Name","Country"); 
    pName="Peak Name"; 
    Height=0; 
} 
public void setpName(String pname) 
{ 
    pName = pname; 
} 
public void setHeight(int height) 
{ 
    Height = height; 
    if(height<0) 
        throw new IllegalArgumentException("Height cannot be negative!"); 
} 
public String getpName() 
{ 
    return pName; 
} 
public double getHeight() 
{ 
    return Height; 
} 
public String toString() 
{ 
    return super.toString() + "; Peak Name: " + pName + "; Height: " + Height; 
} 
@Override
public int compareTo(Vrah o) 
{ 
    if(Height<o.Height)return -1; 
    if(Height>o.Height)return 1; 
    else return 0; 
} 
}

Chain Comparator:

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ChainComparator implements Comparator<Vrah> {

private List<Comparator<Vrah>> listComparators;

@SafeVarargs
public ChainComparator(Comparator<Vrah>... comparators) {
    this.listComparators = Arrays.asList(comparators);
}

public int compare(Vrah vr1, Vrah vr2) {
    for (Comparator<Vrah> comparator : listComparators) {
        int result = comparator.compare(vr1, vr2);
        if (result != 0) {
            return result;
        }
    }
    return 0;
}
}

高度比较器:

 import java.util.Comparator;
 public class HeightComparator implements Comparator<Vrah> {

  @Override
    public int compare(Vrah vr1, Vrah vr2) {
        return (int) (vr1.getHeight() - vr2.getHeight());
    }
}

国家比较者:

import java.util.Comparator;
public class CountryComparator implements Comparator<Vrah> {

@Override
public int compare(Vrah vr1, Vrah vr2) {
    return vr1.getCountry().compareTo(vr2.getCountry());
}
}

Public Class Varhove:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;


public class Varhove{

private Set<Vrah>vSet = new TreeSet<Vrah>();
private String inFile = null;
private String outFile = null;

 public Varhove(String infile, String outfile) throws IOException, FileNotFoundException {
     inFile = infile;
     outFile = outfile;

 @SuppressWarnings("resource")
 RandomAccessFile raf = new RandomAccessFile(inFile,"rw");
 String temp_data="";

 do {
     temp_data="";
     temp_data=raf.readLine();

     if(temp_data != null){
     String[] data = temp_data.split(" ");
     String mname = String.valueOf(data[0]);
     String country = String.valueOf(data[1]);
     String pname = String.valueOf(data[2]);
     int height = Integer.parseInt(data[3]);
     vSet.add(new Vrah(mname, country, pname, height));
     }   
     } while((temp_data != null) && (temp_data.compareTo("") != 0));
     raf.close();
     }

 public void write() throws IOException,FileNotFoundException {
     if(outFile==null)
     return;
     File original = new File(outFile);
     original.delete();

     BufferedWriter out = new BufferedWriter(new FileWriter(outFile));
     for(Vrah it : vSet){
                out.write(it.getmName() + " " + it.getCountry() + " " + it.getpName() + " " + it.getHeight());
                out.newLine();
     }
     out.close();
     }

 public void printColl(){
 for(Vrah it : vSet)
 System.out.print(it.toString()+"\n");
 }
}

主类:

import java.awt.List;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;



public class Main {

public static void main(String[] args) {

    Varhove v_Coll;
    System.out.println("Enter one of the following commands:");
    System.out.println("1 - something..");
    System.out.println("2 - something else..");
    System.out.println("3 - exit");
    @SuppressWarnings("resource")
    Scanner scanchoice = new Scanner(System.in);
    System.out.println();
     int choiceentry = -1;

     do {
            System.out.println("Enter \"1\", \"2\" or \"3\"");
            choiceentry = scanchoice.nextInt();

            switch (choiceentry)
            {
                case 1:
                     try {
                          v_Coll =  new Varhove("E:\\Programs\\Projects\\Java\\JavaProjectX\\inFile.txt", "E:\\Programs\\Projects\\Java\\JavaProjectX\\outFile.txt");
                          v_Coll.printColl();
                          v_Coll.write();
                         System.out.println("Data successfully saved.\n");
                     }
                     catch (FileNotFoundException e) {
                         e.printStackTrace();
                         } catch (IOException e) {
                         e.printStackTrace();
                         }
                    break;
                case 2: 
                    Collections.sort(v_Coll, new ChainComparator(
                            new HeightComparator(),
                            new CountryComparator())
                    );
                    break;
                case 3: 
                    // .. exit program
                    break;
                default:
                    System.out.println("Choice must be a value between 1 and 3.");
            }   
        } while (choiceentry != 3);
}
}

所以我的第一个问题是,如何创建一个向数组添加新对象的方法,例如菜单中有一个选项,允许您从键盘添加新的mName,Country,pName和Height。

我的第二个问题是关于这一行的错误:

                case 2: 
                    Collections.sort(v_Coll, new ChainComparator(
                            new HeightComparator(),
                            new CountryComparator())
                    );
                    break;

我使用ChainedComparator在多个字段中对数组进行排序,但似乎存在一个问题:类型集合中的方法排序不适用于参数。我知道它不是在其他类中实现Comparable,但有没有办法解决它并仍然使用ChainedComparator。任何帮助或示例将不胜感激。谢谢你的时间。

1 个答案:

答案 0 :(得分:0)

I figured it out. It was misplaced use of Collection.sort. I created a new method/function in Varhove class, that makes the treeset collection into an array one, and then I used Collection.sort.