gpt4 book ai didi

java - 如何比较节点列表中的对象?

转载 作者:太空宇宙 更新时间:2023-11-04 06:33:38 24 4
gpt4 key购买 nike

我正在尝试编写一个接受对象并将其与节点列表进行比较的方法。然后它将该列表中小于它的每个元素添加到一个新列表中。我非常接近,但前两个元素没有复制过来。

public LList<String> getAllLessThan(Comparable<T> anObject) {
LList<String> newList = new LList();
Node currentNode = firstNode;
for (int i = 0; i < length; i++)
{
if (currentNode.data.compareTo((T) anObject) == -1)
{
newList.add((String) currentNode.data);
}
currentNode = currentNode.next;
}
return newList;
}

列表的前两个元素应该包含在内,但被省略了。

    String[] names = {"Abby", "Bobby", "Carla", "Doug"};
LList<String> nameList = new LList(names, 4);

String[] newNames = {"Edgar", "Frank"};
nameList.addAll(newNames);
System.out.println("Output should be Abby, Bobby, Carla, Doug, Edgar, Frank");
nameList.display();
System.out.println();

nameList.add("Carrie");
LList<String> newList = nameList.getAllLessThan("Doug");
System.out.println("Output should be Abby, Bobby, Carla, Carrie");
newList.display();
System.out.println();

最佳答案

String.compareTo()

If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:

this.charAt(k)-anotherString.charAt(k)

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:

this.length()-anotherString.length()

String1.compareTo(String2) 方法返回:

0 when strings are equal
> 0 when String1 > String2
< 0 when String1 < String2

改变

if (currentNode.data.compareTo((T) anObject) == -1)

if (currentNode.data.compareTo((T) anObject) < 0)

关于java - 如何比较节点列表中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25736189/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com