简体   繁体   English

compareTo无法正常工作

[英]compareTo does not work properly

I want to sort a input.txt file and save it in output.txt for instance. 我想对一个input.txt文件进行排序,然后将其保存在output.txt中。 I use the insertion sort algorithm. 我使用插入排序算法。 Now my problem: the compareTo method seems to work incorrectly (or at least not how I want to to work). 现在我的问题是:compareTo方法似乎无法正常工作(或者至少不是我想要的工作方式)。 It returns integer greater than 1 thus the algorithm does not really especially for negative numbers. 它返回大于1的整数,因此该算法实际上并不特别适用于负数。 I hope you guys can help me with that problem, thanks! 我希望你们能帮助我解决这个问题,谢谢!

Thats my code: 那就是我的代码:

import java.util.ArrayList;
import java.io.*;

class Isort
{
    public static void main(String[] args)
    {   
        if(args[0].equals("int"))
        {
            ArrayList<Integer> array = new ArrayList<Integer>();
            sort(array, args[1], args[2]);
        }
        else if(args[0].equals("float"))
        {
            ArrayList<Float> array = new ArrayList<Float>();
            sort(array, args[1], args[2]);
        }
        else if(args[0].equals("String"))
        {
            ArrayList<String> array = new ArrayList<String>();
            sort(array, args[1], args[2]);
        }
        else
        {
            //do nothing
        }
    }
    public static <T extends Comparable<T>> void sort(ArrayList<T> array, String input, String output)
    {   
        try
        {
            File file = new File(input);
            BufferedReader reader = new BufferedReader(new FileReader(file));       
            reader.mark((int)file.length() + 1); 
            int count = 0;          
            while(reader.readLine() != null)
            {
                count++;
            }
            reader.reset();
            for(int i = 0; i<count; i++)
            {
                array.add((T)(reader.readLine()));
            }
            reader.close();

            int j;
            T temp;
            for(int i = 1; i < array.size(); i++)
            {
                j = i;
                while(j > 0 && array.get(j-1).compareTo(array.get(j)) > 0)
                {
                    temp = array.get(j);
                    array.set(j,array.get(j-1));
                    array.set(j-1,temp);
                    j -= 1;
                    System.out.println(array);
                }
            }
            PrintWriter writer = new PrintWriter(output);
            for(int i = 0; i<array.size(); i++)
            {
                writer.write(String.valueOf(array.get(i)));
                writer.write(System.getProperty ("line.separator")); 
            }
            writer.flush();
            writer.close();
        }
        catch(FileNotFoundException e)
        {

        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

I believe you are confused by the use of generics. 我相信您对泛型的使用感到困惑。 You are making generic ArrayLists of Integer , Long and String . 您正在创建IntegerLongString通用ArrayLists You are then reading a line of text and attempting to cast it to T . 然后,您正在阅读一行文本,并尝试将其强制转换为T

This will not do anything at runtime due to type-erasure. 由于类型擦除,此操作在运行时不会执行任何操作。 In all of the cases above (int, long and string) you will be passing an ArrayList<Object> and adding String to the list. 在上述所有情况下(int,long和string),您都将传递ArrayList<Object>并将String添加到列表中。 When you read the String from the file the cast doesn't do anything except cast it to an Object which String already is. 当您从文件中读取String ,强制转换除了将其String已经是StringObject外,不会执行任何操作。 So unless the compareTo of String matches your requirements for int and long this will not work. 因此,除非StringcompareTo满足您对int的要求,并且long不能正常工作。

In reply to comment... 回复评论...

That's the point. 这才是重点。 Casting to T or really using generics at all in this case don't do what you need. 在这种情况下,强制转换为T或完全使用泛型都无法满足您的需求。 In all cases you are reading and comparing String . 在所有情况下,您都在阅读和比较String Instead you need to have three methods readInt , readLong and readString and call the appropriate one based on what you are expecting. 相反,您需要具有三种方法readIntreadLongreadString并根据您的期望调用适当的一种。 One option would be to use an interface of readNextValue and pass in an appropriate implementation depending on the situation. 一种选择是使用readNextValue接口,并根据情况传递适当的实现。

I suggest you to using a " Comparator " class in " Collections.sort(...) " method. 我建议您在“ Collections.sort(...) ”方法中使用“ Comparator ”类。 You can find an example here-> http://www.vogella.com/blog/2009/08/04/collections-sort-java/ . 您可以在此处找到一个示例-> http://www.vogella.com/blog/2009/08/04/collections-sort-java/

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

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