java android中的类对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11249101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:23:54  来源:igfitidea点击:

Array of class objects in android

javaandroidarraysclass

提问by steve.watson128

I have constructed a class to mimic a C# struct:

我构造了一个类来模拟 C# 结构:

public class Favourite {
    protected  String favName;
    protected  String favText;
    protected String favDelay;
    protected GeoPoint favPoint;
    protected Uri favUri;
}

I want to create an array of this class:

我想创建这个类的数组:

Favourite[] fav;

When I try to access this array:

当我尝试访问此数组时:

fav[s].favName = bufr;

I get a NullPointerException. bufrdoes contain data. I have tracked it down to accessing the array as the following code:

我得到一个空指针异常。 bufr确实包含数据。我已经追踪到访问数组,如下代码:

fav[s].favName = "";

also produces a NullPointerException.

还会产生 NullPointerException。

I have searched high and low for some indication as to whether or not what I am doing is allowed but cannot find anything.

我已经搜索了一些关于我正在做的事情是否被允许但找不到任何东西的迹象。

I suppose my questions are:

我想我的问题是:

Are you allowed to create an array of a class object? If so, how do you refer to that array?

你可以创建一个类对象的数组吗?如果是这样,您如何引用该数组?

I know I could do this using five separate arrays of the variables but I feel that putting them into a class gives a better structure and is more elegant (I like elegance).

我知道我可以使用五个单独的变量数组来做到这一点,但我觉得将它们放在一个类中可以提供更好的结构并且更优雅(我喜欢优雅)。

回答by Louis Wasserman

The problem is that fav[s]is null.

问题是它fav[s]是空的。

I don't know about C#, but in Java, you have to initialize the elements of the array individually; you can't just declare the array and get it automatically filled.

我不了解 C#,但在 Java 中,您必须单独初始化数组的元素;你不能只声明数组并让它自动填充。

You're going to have to loop through favand fill it with new Favouriteobjects.

您将不得不循环fav并用新Favourite对象填充它。

Either assign fav[s] = new Favourite()the first time you use fav[s], or initialize it all at once by doing

要么分配fav[s] = new Favourite()第一次使用fav[s],要么通过执行一次全部初始化

for (int i = 0; i < fav.length; i++) {
  fav[s] = new Favourite();
}

回答by David Wasser

Favourite[] fav = new Favourite[23]; // Allocate an array of 23 items

Now you have 23 of them!

现在你有 23 个!

回答by Carl Manaster

You need to put items into the array. The declared array simply has null in each slot; you need to do something like fav[s] = new Favourite().

您需要将项目放入数组中。声明的数组在每个插槽中都只有空值;你需要做类似的事情fav[s] = new Favourite()