简体   繁体   English

排序前删除所有空数组值

[英]Remove all null array values before sorting

I have been getting some errors. 我遇到了一些错误。 My array looks like this: 我的数组如下所示:

 String words[] = new String[50000];

The user is asked to input values into the array 要求用户将值输入数组

words[i]=c.readLine();

The program will exit the infinite for loop once duplicated values are inputed. 输入重复的值后,程序将退出无限循环。 Now the program must sort the array in alphabetical order, yet it is trying to sort some of the null values and returns errors. 现在,程序必须按字母顺序对数组进行排序,但是它正在尝试对某些空值进行排序并返回错误。

Arrays.sort(words, String.CASE_INSENSITIVE_ORDER);         
for (int a = 0; a < words.length; a++) {
    c.println(words[a]);
}

This program will work only if the user inputs exactly 50000 values. 仅当用户输入正好50000个值时,此程序才有效。 I am unable to guess how many values the user will input, how do I solve this? 我无法猜测用户将输入多少个值,我该如何解决?

I am thinking I have to somehow remove all null values before alphabetically sorting. 我想我必须以某种方式删除所有空值,然后再按字母顺序排序。 Any ideas? 有任何想法吗?

use ArrayList if you are not sure of the size . 如果不确定size使用ArrayList don't hardcode it. 不要硬编码它。

But if you insist to use array , what you can try: 但是,如果您坚持使用array ,可以尝试:

int notNull=words.length;    
for(int i= 0;i<words.length;i++){
    if(words[i]==null){
        notNull=i;
    break;
}
}
String[] newWords=Arrays.copyOfRange(words, 0, notNull);

newWords array will be your new array without null values newWords数组将是没有空值的新数组

You could count the inputed Values and Sort only the non null values using 您可以计算输入的值,并使用来仅对非空值进行排序

Arrays.sort(words, 0,inputCount, String.CASE_INSENSITIVE_ORDER);

where inputCount is the count of the encapsulating endless while loop. 其中inputCount是封装的while循环的计数。


You could also modify your for-loop 您还可以修改for循环

for (int a = 0; a < inputCount; a++) {

You could use an ArrayList or a Set (or any other dynamically-sizing collection) to track how many strings are actually input. 您可以使用ArrayListSet (或任何其他动态调整大小的集合)来跟踪实际输入的字符串数。

If you want to stick with a pre-created array, you could count how many lines are actually read and only loop up to that amount. 如果您要坚持使用预先创建的数组,则可以计算实际读取的行数,并且最多可以循环到该数量。

You could use a binary insertion sort when the strings are being input. 输入字符串时,可以使用二进制插入排序。 This will be a faster search for duplicates and will give you an ordered list ready to be output. 这样可以更快地搜索重复项,并为您提供准备好输出的有序列表。

There are a lot of options, but this doesn't seem to be a good one. 有很多选择,但这似乎不是一个好选择。 Since you have 50000 spots, what happens if the user tries to enter one more than that? 既然您有50000点,那么如果用户尝试输入多于该点会发生什么?

You could use a java.util.Set to hold your words. 您可以使用java.util.Set来保存您的单词。 That way you don't have to deal with initializing or extending the array. 这样,您不必处理初始化或扩展数组。

Instead of worrying about the null values in your set, think of it like this: 不用担心集合中的空值,可以这样考虑:

  • If you're comparing against one non-null value and one null value, the non-null value wins. 如果要与一个非空值和一个空值进行比较,则以非空值为准。
  • If you're comparing against two non-null values, neither wins. 如果要与两个非null值进行比较,则两个都不赢。

You can create a custom Comparator<String> , and use it in Arrays#sort . 您可以创建一个自定义Comparator<String> ,并在Arrays#sort使用它。 As an aside, String.CASE_INSENSITIVE_ORDER is also a Comparator<String> , but it doesn't quite fill the need that you seem to have. String.CASE_INSENSITIVE_ORDERString.CASE_INSENSITIVE_ORDER也是Comparator<String> ,但它并不能完全满足您的需求。

Here's an example implementation: 这是一个示例实现:

public class NullAwareStringComparator implements Comparator<String> {

    @Override
    public int compare(String o1, String o2) {
        if (o1 == null && o2 == null) {
            return 2;
        } else if (o1 == null) {
            return 1;
        } else if (o2 == null) {
            return -1;
        } else {
            return o1.compareToIgnoreCase(o2);
        }
    }
}

You would then call your sort method with it as such: 然后,您可以这样调用您的sort方法:

Arrays.sort(words, new NullAwareStringComparator());

This puts all of the null values at the end of the array. 这会将所有null值放在数组的末尾。 If you want the reverse ordering, flip the sign of the numbers returned in the compare method. 如果要反向排序,请翻转compare方法中返回的数字的符号。

Alternatively , if you don't know/care how many elements you can hold, consider using a TreeSet<String> instead - this has the added benefit of ignoring duplicate entries. 另外 ,如果您不知道/不在乎可以保留多少个元素,请考虑改用TreeSet<String> -这具有忽略重复条目的额外好处。

Set<String> sortedStrings = new TreeSet<>(new NullAwareStringComparator());

You could also use String.CASE_INSENSITIVE_ORDER as the comparator instead, since at this point, you're not nearly as worried about null entries as you previously were: 您还可以使用String.CASE_INSENSITIVE_ORDER作为比较器,因为在这一点上,您几乎不像以前那样担心null条目:

Set<String> sortedStrings = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);

...and to sort the collection, you would call Collections.sort() . ...并对集合进行排序,您可以调用Collections.sort()

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

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