如何在 Java 中声明动态字符串数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3601490/
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
How can I declare dynamic String array in Java
提问by sivaraj
I am using String Array declare as zoom z[]=new String[422];
. But this array stores value from 0
to 32
, so I got null pointer exception
after looping value 32
.
我正在使用字符串数组声明为zoom z[]=new String[422];
. 但是这个数组存储来自0
to 的值32
,所以我null pointer exception
在循环 value 之后得到了32
。
How to solve this problem in java?
在java中如何解决这个问题?
How can I declare a dynamic array in java ?
如何在 java 中声明动态数组?
采纳答案by Chadwick
You want to use a Set
or List
implementation (e.g. HashSet
, TreeSet
, etc, or ArrayList
, LinkedList
, etc..), since Java does not have dynamically sized arrays.
你想用一个Set
或List
实现(例如HashSet
,TreeSet
等等,或者ArrayList
,LinkedList
等..),因为Java没有动态大小的数组。
List<String> zoom = new ArrayList<>();
zoom.add("String 1");
zoom.add("String 2");
for (String z : zoom) {
System.err.println(z);
}
Edit:Here is a more succinct way to initialize your List with an arbitrary number of values using varargs:
编辑:这是使用varargs使用任意数量的值初始化 List 的更简洁的方法:
List<String> zoom = Arrays.asList("String 1", "String 2", "String n");
回答by mhshams
no, there is no way to make array length dynamic in java. you can use ArrayList
or other List
implementations instead.
不,没有办法在 java 中使数组长度动态化。您可以改用ArrayList
或 其他List
实现。
回答by Kelly S. French
Maybe you are looking for Vector
. It's capacity is automatically expanded if needed. It's not the best choice but will do in simple situations. It's worth your time to read up on ArrayList
instead.
也许您正在寻找Vector
. 如果需要,它的容量会自动扩展。这不是最好的选择,但在简单的情况下会做。值得您花时间阅读ArrayList
。
回答by user698816
What your looking for is the DefaultListModel - Dynamic String List Variable.
您要寻找的是 DefaultListModel - 动态字符串列表变量。
Here is a whole class that uses the DefaultListModel as though it were the TStringList of Delphi.The difference is that you can add Strings to the list without limitation and you have the same ability at getting a single entry by specifying the entry int.
这是一个使用 DefaultListModel 的整个类,就好像它是 Delphi 的 TStringList 一样。不同之处在于您可以无限制地将字符串添加到列表中,并且您可以通过指定条目 int 来获取单个条目。
FileName: StringList.java
文件名:StringList.java
package YOUR_PACKAGE_GOES_HERE;
//This is the StringList Class by i2programmer
//You may delete these comments
//This code is offered freely at no requirements
//You may alter the code as you wish
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
public class StringList {
public static String OutputAsString(DefaultListModel list, int entry) {
return GetEntry(list, entry);
}
public static Object OutputAsObject(DefaultListModel list, int entry) {
return GetEntry(list, entry);
}
public static int OutputAsInteger(DefaultListModel list, int entry) {
return Integer.parseInt(list.getElementAt(entry).toString());
}
public static double OutputAsDouble(DefaultListModel list, int entry) {
return Double.parseDouble(list.getElementAt(entry).toString());
}
public static byte OutputAsByte(DefaultListModel list, int entry) {
return Byte.parseByte(list.getElementAt(entry).toString());
}
public static char OutputAsCharacter(DefaultListModel list, int entry) {
return list.getElementAt(entry).toString().charAt(0);
}
public static String GetEntry(DefaultListModel list, int entry) {
String result = "";
result = list.getElementAt(entry).toString();
return result;
}
public static void AddEntry(DefaultListModel list, String entry) {
list.addElement(entry);
}
public static void RemoveEntry(DefaultListModel list, int entry) {
list.removeElementAt(entry);
}
public static DefaultListModel StrToList(String input, String delimiter) {
DefaultListModel dlmtemp = new DefaultListModel();
input = input.trim();
delimiter = delimiter.trim();
while (input.toLowerCase().contains(delimiter.toLowerCase())) {
int index = input.toLowerCase().indexOf(delimiter.toLowerCase());
dlmtemp.addElement(input.substring(0, index).trim());
input = input.substring(index + delimiter.length(), input.length()).trim();
}
return dlmtemp;
}
public static String ListToStr(DefaultListModel list, String delimiter) {
String result = "";
for (int i = 0; i < list.size(); i++) {
result = list.getElementAt(i).toString() + delimiter;
}
result = result.trim();
return result;
}
public static String LoadFile(String inputfile) throws IOException {
int len;
char[] chr = new char[4096];
final StringBuffer buffer = new StringBuffer();
final FileReader reader = new FileReader(new File(inputfile));
try {
while ((len = reader.read(chr)) > 0) {
buffer.append(chr, 0, len);
}
} finally {
reader.close();
}
return buffer.toString();
}
public static void SaveFile(String outputfile, String outputstring) {
try {
FileWriter f0 = new FileWriter(new File(outputfile));
f0.write(outputstring);
f0.flush();
f0.close();
} catch (IOException ex) {
Logger.getLogger(StringList.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
OutputAsmethods are for outputting an entry as int, double, etc... so that you don't have to convert from string on the other side.
OutputAs方法用于将条目输出为 int、double 等......这样您就不必在另一侧从字符串转换。
SaveFile & LoadFileare to save and load strings to and from files.
SaveFile & LoadFile用于在文件中保存和加载字符串。
StrToList & ListToStrare to place delimiters between each entry.
StrToList & ListToStr用于在每个条目之间放置分隔符。
ex. 1<>2<>3<>4<> if "<>" is the delimiter and 1 2 3 & 4 are the entries.
前任。1<>2<>3<>4<> 如果 "<>" 是分隔符并且 1 2 3 & 4 是条目。
AddEntry & GetEntryare to add and get strings to and from the DefaultListModel.
AddEntry 和 GetEntry用于在 DefaultListModel 中添加和获取字符串。
RemoveEntryis to delete a string from the DefaultListModel.
RemoveEntry是从 DefaultListModel 中删除一个字符串。
You use the DefaultListModel instead of an array here like this:
您在此处使用 DefaultListModel 而不是数组,如下所示:
DefaultListModel list = new DefaultListModel();
//now that you have a list, you can run it through the above class methods.
回答by Antonin Stefanutti
The Array.newInstance(Class<?> componentType, int length)
method is to be used to create an array with dynamically length.
该Array.newInstance(Class<?> componentType, int length)
方法用于创建具有动态长度的数组。
Multi-dimensional arrays can be created similarly with the Array.newInstance(Class<?> componentType, int... dimensions)
method.
可以使用该Array.newInstance(Class<?> componentType, int... dimensions)
方法类似地创建多维数组。