我发现有必要评论 @JordiCastilla 解决方案在完整的意义上是不正确的。如果项目类型具有正确的等于,则它可能是正确的,因为在 Collections.indexOfSubList 的情况下,您会调用列表元素类型 equals。
/**
* Compares the specified object with this list for equality. Returns
* <tt>true</tt> if and only if the specified object is also a list, both
* lists have the same size, and all corresponding pairs of elements in
* the two lists are <i>equal</i>. (Two elements <tt>e1</tt> and
* <tt>e2</tt> are <i>equal</i> if <tt>(e1==null ? e2==null :
* e1.equals(e2))</tt>.) In other words, two lists are defined to be
* equal if they contain the same elements in the same order. This
* definition ensures that the equals method works properly across
* different implementations of the <tt>List</tt> interface.
*
* @param o the object to be compared for equality with this list
* @return <tt>true</tt> if the specified object is equal to this list
*/
boolean equals(Object o);
然而,这与文化无关,并且在字符串类型不正确的情况下。举个例子:
String a = "ss";
String b = "ß"; //german "ss" character
Assert.IsTrue(a.equals(b)); //in java, this will return false even in DE locale
我认为其背后的原因是字符数不匹配 - 在任何情况下都是不正确的。你会认为“至少他们的基础知识是正确的”——你错了:
“您应该意识到国际化和本地化问题
完整的 Unicode 字符串不使用 [String] 方法处理。为了
例如,当您比较两个字符串以确定哪个是
'greater',字符串中的字符通过它们的数字进行比较
Unicode 值,而不是它们的本地化顺序概念。”
然而,在 Unicode 中,相同的字符串可以有 多个 表示,并且它们不会等同。类型 String 是一个示例,但您可以使用任何自定义数据类型。
长话短说:确保您的项目类型 equals 具有正确的实现。
这可能是微不足道的错误的另一个例子如下:
List arrlistsrc = new ArrayList();
List arrlisttarget = new ArrayList();
arrlistsrc.add("A");
arrlistsrc.add("B");
arrlistsrc.add("C");
arrlisttarget.add("A");
arrlisttarget.add("C");
int index = Collections.indexOfSubList(arrlistsrc, arrlisttarget); // this will be -1
第一个列表包含第二个并且它们具有相同的顺序,但在元素之间目标元素源包含其他元素。
发现你可以在行中使用一些东西:
boolean ContainsOrderedSublist<T>(IList<T> arrlistsrc, IList<T> arrlisttarget){
int slider = 0;
for (String val: arrlisttarget ) {
slider = arrlistsrc.indexOf(val, slider);// or use culture independent version
if(slider < 0) break;
}
return slider < 0;
}
(注意:代码示例未从头测试和编写)