我想创建一个代码,帮助我将'allWords'ArrayList中的元素复制到'distinctWords'。但他在不同的单词ArrayList中的时间我想要一个单词只出现一个,消除了“distinctWords”ArrayList中的冗余。
这是我提出的代码,我没有输出。
import java.util.ArrayList;
public class copyElements {
static ArrayList<String> distinctWords = new ArrayList<String> ();
static ArrayList<String> allWords = new ArrayList<String> ();
static int allWordsCount = 0;
static int distinctWordsCount;
static int tracker;
public static void main(String[] args) {
allWords.add("you");
allWords.add("want");
allWords.add("to");
allWords.add("go");
allWords.add("to");
allWords.add("dubai");
allWords.add("and");
allWords.add("you");
allWords.add("also");
allWords.add("want");
allWords.add("to");
allWords.add("go");
allWords.add("to");
allWords.add("seychelles");
//printing all items in the 'allwords' arraylist
//System.out.println("CONTENTS OF 'ALL WORDS' ARRAYLIST : ");
distinctWords.add(0,allWords.get(0));
distinctWordsCount = 1;
int i = 1;
for(int j = 1; j <= distinctWords.size(); j++){
if(i < allWords.size()){
tracker = 0;
if (tracker == j){
distinctWords.add(j, allWords.get(i));
System.out.println("\t\t\t" + distinctWords.get(j));
distinctWordsCount ++;
i++;
} else
if (tracker != j){
if(allWords.get(i) != distinctWords.get(tracker)){
//distinctWords.add(allWords.get(i));
//distinctWordsCount ++;
tracker++;
}
else
if(allWords.get(i) == distinctWords.get(tracker)){
i++;
}
//System.out.println("CONTENTS OF 'ALL WORDS' ARRAYLIST : ");
//System.out.println("\t\t\t" + distinctWords.get(j));
}
}
//System.out.println("\t\t\t" + distinctWords.get(j));
}
//System.out.println("\n\nTHE NUMBER OF ITEMS IN THE 'ALLWORDS' ARRAYLIST IS : " + allWords.size());
//System.out.println("\n\nTHE NUMBER OF ITEMS IN THE 'DISTINCTWORDS' ARRAYLIST IS : " + allWords.size());
System.out.println("\n\nITEMS IN THE 'DISTINCTWORDS' ARRAYLIST ARE : " + distinctWords.size());
}
}
答案 0 :(得分:0)
//al1 and al2 are ArrayList<Object>
for(Object obj:al1){
if(!al2.contains(obj))
al2.add(obj);
}
答案 1 :(得分:0)
以下代码如何:
for (int i = 0, size = allWords.size(); i < size; i++)
{
String word = allWords.get(i);
// add the word if it is not in distinctWords
if (!distinctWords.contains(word))
{
distinctWords.add(word);
}
}
如果您不关心单词的顺序,那么您可以按建议使用Set。
Set<String> distinctSet = new HashSet<String>(allWords);
// if you want the set put into your other arrayList
distinctWords.addAll(distinctSet);
答案 2 :(得分:0)
我认为这可以为您提供一系列不同的词语。
Set<String> distinctWords = new HashSet<>(allWords);
如果你确实需要一个数组,你可以这么做:
ArrayList<String> distinctWordsArr = new ArrayList<>(distinctWords);