如何在Java中声明动态字符串数组

时间:2022-05-04 21:27:45

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.

我使用String Array declare作为zoom z[]=new String[422];但是这个数组将值从0存储到32,所以我在循环值32之后得到了空指针异常。

How to solve this problem in java?

如何用java解决这个问题?

How can I declare a dynamic array in java ?

如何在java中声明动态数组?

5 个解决方案

#1


40  

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.

您希望使用一个集合或列表实现(例如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<String> zoom = Arrays.asList("String 1", "String 2", "String n");

#2


5  

no, there is no way to make array length dynamic in java. you can use ArrayList or other List implementations instead.

不,在java中没有办法使数组长度动态。您可以使用ArrayList或其他列表实现。

#3


3  

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.

也许你在寻找向量。如果需要,它的容量会自动扩展。这不是最好的选择,但在简单的情况下也可以。值得你花时间阅读ArrayList。

#4


0  

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);
        }
    }
}

OutputAs methods 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 & LoadFile are to save and load strings to and from files.

SaveFile & LoadFile用于保存和加载文件之间的字符串。

StrToList & ListToStr are 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<> if "<>"为分隔符,1 2 3 & 4为条目。

AddEntry & GetEntry are to add and get strings to and from the DefaultListModel.

AddEntry和GetEntry将在DefaultListModel中添加和获取字符串。

RemoveEntry is 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.

#5


0  

The Array.newInstance(Class<?> componentType, int length) method is to be used to create an array with dynamically length.

Array.newInstance(类< ?方法是用来创建一个动态长度的数组。

Multi-dimensional arrays can be created similarly with the Array.newInstance(Class<?> componentType, int... dimensions) method.

可以使用Array.newInstance(类 组件类型,int……维)方法。

#1


40  

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.

您希望使用一个集合或列表实现(例如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<String> zoom = Arrays.asList("String 1", "String 2", "String n");

#2


5  

no, there is no way to make array length dynamic in java. you can use ArrayList or other List implementations instead.

不,在java中没有办法使数组长度动态。您可以使用ArrayList或其他列表实现。

#3


3  

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.

也许你在寻找向量。如果需要,它的容量会自动扩展。这不是最好的选择,但在简单的情况下也可以。值得你花时间阅读ArrayList。

#4


0  

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);
        }
    }
}

OutputAs methods 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 & LoadFile are to save and load strings to and from files.

SaveFile & LoadFile用于保存和加载文件之间的字符串。

StrToList & ListToStr are 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<> if "<>"为分隔符,1 2 3 & 4为条目。

AddEntry & GetEntry are to add and get strings to and from the DefaultListModel.

AddEntry和GetEntry将在DefaultListModel中添加和获取字符串。

RemoveEntry is 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.

#5


0  

The Array.newInstance(Class<?> componentType, int length) method is to be used to create an array with dynamically length.

Array.newInstance(类< ?方法是用来创建一个动态长度的数组。

Multi-dimensional arrays can be created similarly with the Array.newInstance(Class<?> componentType, int... dimensions) method.

可以使用Array.newInstance(类 组件类型,int……维)方法。