0

我基本上需要知道是否可以将 1 arrayList 更改为另一个 arrayList,然后关联 arrayList 1 中的哪个项目,arrayList 2 中的项目来自,而不使用模式查找器。很难解释,所以用一个简单的例子来说明:

给定文件输入:

Feline:
Cat Lion
Cheetah

Canine:
Dog
Wolves Fox

我使用以下方法将文件拆分为每个段落:

String strLine;
String [] paragraph = strLine.split("");

从这里我通过在高级 for 循环中使用 add 方法将每个项目添加到 arrayList。

这应该给我们留下第一个arrayList:

[Feline: Cat Lion Cheetah, Canine: Dog Wolves Fox]

从那里需要使用正则表达式 \\s+ 将每个项目拆分为单独的单词。使用另一个高级 for 循环应该很容易。

这应该给我们留下第二个arrayList:

[Feline:, Cat, Lion, Cheetah, Canine:, Dog, Wolves, Fox]

我需要知道的是,是否无论如何让程序意识到第二个arrayList 中的单词Cheetah 源自第一个arrayList 中的第一个项目,而不必在第一个arraylist 中搜索第二个arrayList 中的项目。关键必须是一个arrayList中的一项源自另一个arrayList。

我基本上需要这样做,因为我有方法可以根据每个段落的第一个单词是什么,对每个段落执行不同的操作。

如果我的解释令人困惑并且对错误的术语感到抱歉,请告诉我,我在解释我的问题时遇到了麻烦。

如果这是可能的,请让我知道如何解决我的问题。

问候

4

2 回答 2

2

当您根据空格字符进行拆分时,我建议保留初始数组列表位置。例如,您定义一个对象如下;

public class MyWord
{
private int pos;

private String word;
public MyWord(int pos,String word)
{
 this.pos = pos;

 this.word = word;
}
//getters and setters
} 

然后当你分裂时,你可以做这样的事情;

List<MyWord>secondList = new ArrayList<MyWord>();
for(int i=0;i<firstList.size();i++)
{
 String[]words = firstList.get(i).split("\\s");
 for(String wordToAdd : words)
 {
  MyWord w = new MyWord(i,wordToAdd);
  secondList.add(w);
 }
}

所以现在你的第二个列表将有一个包含单词的对象以及它包含在第一个列表中的原始索引。

啤酒花这有帮助。

于 2013-01-13T15:29:33.140 回答
1

Your program is never going to 'realize' anything. Each of the Java collections has a specified semantics, and they do no more and no less that what they are documented to do.

java.util.List stores an ordered list of of objects. It does not detect duplicates. It does not maintain associations with anything else. You can ask a list 'do you contain X'? with the contains method. This takes time proportional to the number of things in the list.

When you store String objects in a list, there is no concept of where they come from. They are just in the list. If you need your second list to contain items that correlate to your first list, you need to code that. If all the second list needs to store is correlations to the first list, it could be a List<Integer>, and for each of those items you search for it in the first list to get the index. So, yes, as you process each of the items for the second list, you need to scan the first list to see if/where it is. It's not clear from your question what you want to have happen if something from the second group was not mentioned at all in the first group.

于 2013-01-13T15:36:05.710 回答