简体   繁体   English

Java,将链接列表与数组进行比较

[英]Java, comparing a Linked List to an Array

Working on a Java program that will read in two different passages, convert both strings to arrays of strings for each word, and then String One to a linked list, which will promptly be sorted into alphabetical order. 使用将读取两个不同段落的Java程序进行工作,将两个字符串都转换为每个单词的字符串数组,然后将String One转换为链接列表,该列表将立即按字母顺序排序。

After the list has been sorted, I get confused. 对列表进行排序后,我感到困惑。 I have a for loop written to get the length of array2 to advance it as needed, but what would be a good loop for advancing through a linked list? 我编写了一个for循环来获取array2的长度以根据需要进行扩展,但是前进通过链表的最佳循环是什么? It may be basic, but nothing comes to mind. 这可能是基本的,但没有想到。

EDIT: Left this bit of information out. 编辑:忽略了这一点信息。 My bad. 我的错。 The point is to compare the array and the linked list word by word, and if two words match up, that word and node will be removed from the linked list. 关键是逐字比较数组和链接列表,如果两个单词匹配,则将从链接列表中删除该单词和节点。

And also, another question regarding the Java LinkedList class, is there a delete function? 而且,关于Java LinkedList类的另一个问题是,是否有删除功能? And if so, does it automatically pull it back and link the two threads? 如果是这样,它是否会自动将其拉回并链接两个线程?

I have already tested to see if the strings are being assigned properly and they are. 我已经测试过,看看是否正确分配了字符串。

The program is below. 该程序在下面。

package algorithm;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;

public class main 
{

    public static void main (String[] args) throws FileNotFoundException
    {   
        String input1 = new Scanner(new File("passage1.txt")).useDelimiter("\\Z").next();
        String input2 = new Scanner(new File("passage2.txt")).useDelimiter("\\Z").next();
        String[] array1 = input1.split(" ");
        String[] array2 = input2.split(" ");

        List<String> list = new LinkedList(Arrays.asList(array1));

        Collections.sort(list);

        int length = array2.length;

        for (int c = 0; c < length; c++)
        {
            // LinkedList loop here


        }
    }
}

Simply you can use boolean removeAll(Collection<?> c) method which is defined in the List interface. 只需使用List接口中定义的boolean removeAll(Collection<?> c)方法即可。 What you have to do is, you need to make as instance of Collection. 您要做的是,需要将其作为Collection的实例。 In your case, 就你而言

List<String> list = new LinkedList(Arrays.asList(array1));
Collections.sort(list);
List<String> toRemove = new LinkedList(Arrays.asList(array2));
list.removeAll(toRemove);

Now the list object will contains the element that are not present in toRemove object. 现在,列表对象将包含toRemove对象中不存在的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM