【问题标题】:Assigning Strings to field of Partially Filled Array将字符串分配给部分填充数组的字段
【发布时间】:2014-11-27 00:25:47
【问题描述】:

我有一个包含大约 80000 多个单词的文本文件。我正在尝试检查这些单词的长度,看看它是否与不使用数组列表输入的数字匹配。

假设一个数组有这些全局变量:

public static int INITIAL_SIZE = 100;
public static int size;
public String[] array = new String[INITIAL_SIZE];

我要创建一个对象:

PartArray part = new PartArray();

还有一个字段:

part.array = new String[INITIAL_SIZE];

(然后继续用另一种方法扩展数组,将初始大小乘以 2,直到它可以包含所有 80000+ 个单词)

但我想将数组中的每个单词都分配到 0、1、2、..... (80000 -1) 到某种程度;

part.array[part.size++] = "aardvark";
.....
part.array[part.size++] = "zymurgy";

以便我可以打印具有此特定长度的单词。

part.array[0];

但是我该怎么做呢?我应该在java中创建另一个类吗?我只是不想在该文本文件中的每个单词前面都加上“String”。

【问题讨论】:

  • 为什么不想使用ArrayList?
  • @JimN 我试图从根本上理解这一点,没有 ArrayList 是否可能?
  • 在我看来,您所描述的是 ArrayList 的实现。所以你可以实现你自己的(在内部使用数组),或者你可以使用现有的 ArrayList。

标签: java arrays loops


【解决方案1】:

我不确定我是否理解你想要做的事情,但据我所知,你想要实现类似于 ArrayList 的东西..

首先让我们澄清一些事情。您发布的代码示例将始终导致 ArrayIndexOutOfBoundsException:

part.array[part.size++] = "aardvark";
.....
part.array[part.size++] = "zymurgy";

无论您的数组有多大,您都会尝试访问该数组之外的内存。 如果你真的不想使用 ArrayList(或任何其他 List),你可能想创建自己的类,它的行为方式类似..

public class StringList{
    public static final int DEFAULT_INITIAL_SIZE = 100;
    public static final float DEFAULT_SCALE_FACTOR = 2;

    private String[] content;
    private float scaleFactor;
    private int counter = 0;

    public StringList(){
        this(DEFAULT_INITIAL_SIZE);
    }

    public StringList(int initialSize){
        this(initialSize, DEFAULT_SCALE_FACTOR);
    }

    public StringList(int initialSize, float scaleFactor){
        this.scaleFactor = scaleFactor;
        content = new String[initialSize];
    }

    public void add(String toAdd){
        //check if we ran out of space for new content..
        if(counter == content.length){
            //create a new array with twice the current arrays size
            String[] temp = new String[(int) (content.length * scaleFactor)];
            //efficiently copy content from current array to temp
            System.arraycopy(content, 0, temp, 0, content.length);
            content = temp;
        }
        content[counter++] = toAdd;
    }

    public String get(int index){
        return content[index];
    }

    public int size(){
        return counter;
    }
}

那个类应该做你需要的一切.. 这是一个简短的例子..

StringList stringList = new StringList();
stringList.add("aardvark");
// add more stuff...
stringList.add("zymurgy");

for (int i = 0; i < stringList.size(); i++) {
    String someText = stringList.get(i);
    // do stuff with your string...
}

【讨论】:

  • 你可以用泛型来做,就像 ArrayList 一样,但我认为这不是你想要做的。如果它实现 List 或 Iterable 也很好 接口,但我们不希望事情变得混乱,是吗? :)
猜你喜欢
  • 1970-01-01
  • 2010-10-09
  • 1970-01-01
  • 2021-12-07
  • 2021-07-23
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多