简体   繁体   English

删除数组中的Null元素

[英]Removing Null elements in an array

I'm reading from an XML file to populate some data structures and I run into this sort of problem when I inspect my final structure: 我正在读取XML文件以填充一些数据结构,当我检查我的最终结构时遇到这种问题:

arrayName
 [0] = null
 [1] = input
 [2] = null
 [3] = input

etc 等等

input is what I want, and the type is my own class. 输入是我想要的,类型是我自己的类。

I'm used to C# so I'd use LINQ to get rid of them normally, idea for doing something like this in Java? 我已经习惯了C#所以我会使用LINQ来正常摆脱它们,想在Java中做这样的事情吗?

I'm going to look at what's wrong with the code that's making it happen but for now I need a quick solution. 我将看看使它发生的代码有什么问题,但是现在我需要一个快速的解决方案。

Ideas? 想法?

EDIT: 编辑:

I found the issue, I create an array of size doc.getChildNodes().getLength(), and when I'm setting elements in the array (while looping through), I check if 我发现了这个问题,我创建了一个大小为doc.getChildNodes()。getLength()的数组,当我在数组中设置元素时(循环遍历),我检查是否

 getNodeType() == Node.ELEMENT_NODE) 

And it doesn't work half the time. 它有一半的时间不起作用。 Problem is, I initialise the array based on the size, so half the array gets filled. 问题是,我根据大小初始化数组,因此数组的一半被填充。

Ideas? 想法?

Arrays are immutable in Java (not their contents , the array itself). 数组在Java中是不可变的(不是它们的内容 ,数组本身)。 There is no such thing as a dynamic sized array or changing of the length. 没有动态大小的数组或更改长度。 So you would iterate, count, create a new array, copy... or use an appropriate datastructure in the first place, maybe even one that capsules the creation of new arrays and offers manipulation methods like ArrayList . 因此,您将首先迭代,计数,创建新数组,复制......或使用适当的数据结构,甚至可以创建新数组,并提供类似ArrayList操作方法。

Something like LINQ does not exist yet, you need some explicit object that capsules the manipulation or filtering. 像LINQ这样的东西还不存在,你需要一些隐藏操作或过滤的显式对象。

If you're not having excessive amounts of data, you could just blend it through a few collections. 如果您没有过多的数据,可以将它混合到一些集合中。

public class Main {
    public static void main(String[] args) {
        String[] arr = {"haha", "hoho", null, "hihi", null };
        System.out.println(Arrays.toString(arr));

        Set<String> set = new HashSet<>(Arrays.asList(arr));
        set.remove(null);
        arr = new String[set.size()];
        arr = set.toArray(arr);

        System.out.println(Arrays.toString(arr));
    }
}

Output: 输出:

[haha, hoho, null, hihi, null]
[hoho, haha, hihi]

Keep in mind that this first allocates the original array, then creates a list from that array, then creates a hashset from that list and eventually puts everything back in the original array. 请记住,这首先分配原始数组,然后从该数组创建一个列表,然后从该列表创建一个哈希集,最终将所有内容放回原始数组中。

If you're having a very large amount of data it might constipate you a little but otherwise it's very easy to read and really just uses built-in features to reach what you want. 如果您拥有非常大量的数据,它可能会让您感到烦躁,但除此之外它非常容易阅读,并且只是使用内置功能来达到您想要的效果。

Unfortunately, there's nothing like LINQ in Java. 不幸的是,在Java中没有像LINQ那样的东西。 The best thing would be probably checking for null beforehand, and only inserting if the element is not null, eg. 最好的事情可能是事先检查null,并且只在元素不为null时才插入,例如。 (assuming your class name is InputClass : (假设您的类名是InputClass

InputClass c = parseFromXml(...);
if (c != null) {
    myList.add(c);
}

Alternatively, you can remove nulls by iterating and copying (I use a list as an intermediary artifact): 或者,您可以通过迭代和复制来删除空值(我使用列表作为中间工件):

InputClass[] removeNulls(InputClass[] original) {
    List<InputClass> nonNulls = new ArrayList<InputClass>();
    for (InputClass i : original) {
        if (i != null) {
            nonNulls.add(i);
        }
    }

    return nonNulls.toArray(new InputClass[0]);
}

You can also use generics and make your method <T> removeNulls(T[] original) instead. 您也可以使用泛型并使您的方法<T> removeNulls(T[] original)代替。

It sounds like you want a method to give you a new Array with the null values removed; 听起来你想要一个方法来为你提供一个删除null值的新数组; perhaps something like this - 也许是这样的 -

public static <T> T[] removeNulls(T[] in) {
  if (in == null) {
    return in;
  }
  Class<?> cls = null;
  List<T> al = new ArrayList<T>();
  for (T t : in) {
    if (t != null) {
      if (cls == null) {
        cls = t.getClass();
      }
      al.add(t);
    }
  }
  @SuppressWarnings("unchecked")
  T[] out = (T[]) Array.newInstance(cls, al.size());
  return al.toArray(out);
}

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

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