gpt4 book ai didi

java - 无法对我的字符串 ArrayList 进行排序

转载 作者:行者123 更新时间:2023-12-01 17:30:08 25 4
gpt4 key购买 nike

我试图按字母顺序对字符串数组列表进行排序,我尝试了一切,从简单的方法:

List<String> theList = new ArrayList<String>();
theList.add("silex");theList.add("soliton");
theList.add("snake");theList.add("supracanon");
Collections.sort(theList);

一些更奇特的东西:

List<String> theList = new ArrayList<String>();
theList.add("silex");theList.add("soliton");
theList.add("snake");theList.add("supracanon");
Collections.sort(
theList,
new Comparator<String>()
{
public int compare(String lhs, String rhs)
{
return lhs.compareTo(rhs);
}
}
);

但是没有任何作用,我做错了什么?谢谢。

ps:我正在查看生成的 ArrayList 的内容,如下所示:

for (String temp:listeProduitPredit){
System.out.println(temp);
}

排序过程前后列表内容不会改变。

================================================== ================================好吧,这是实际的代码,我有一个 EJB 进行数据库访问,它的方法之一是返回字符串列表。

字符串列表应该像字典中一样排序(按字母顺序)但是 'Collections.sort(rList)' 不执行任何操作(输入 = 输出)

public List<String> rechercherListeDeProduitCommencantPar(Integer gammeId, Integer familleId, String debutProduit) {
Criteria c = HibernateUtil.getSessionFactory().getCurrentSession().createCriteria(Produit.class, "p");
c.createAlias("p.famille", "f").createAlias("f.gamme", "g");

if (gammeId != null) {
c.add(Restrictions.eq("g.id", gammeId));
}
if (familleId != null) {
c.add(Restrictions.eq("f.id", familleId));
}
if (!debutProduit.equals("")) {
c.add(Restrictions.like("p.designation", debutProduit+"%"));
}

//getting only the interesting intels (product's name)
List<String> rList = new ArrayList<String>();
List<Produit> pList = c.list();
for (Produit p : pList){
rList.add(p.getDesignation());
}
Collections.sort(rList);
return rList;
}

这是在 Jboss AS 5.1 服务器上运行的,我通过使用 for before 和 after 对其进行了测试,列表没有按字母顺序排序,但确实进行了一些修改:

18:44:07,961 INFO  [STDOUT] Before=========
18:44:07,961 INFO [STDOUT] SUMO VIE
18:44:07,961 INFO [STDOUT] soliton
18:44:07,961 INFO [STDOUT] snake
18:44:07,961 INFO [STDOUT] SupraCanon
18:44:07,961 INFO [STDOUT] Segolene
18:44:07,961 INFO [STDOUT] silex
18:44:07,962 INFO [STDOUT] After=========
18:44:07,962 INFO [STDOUT] SUMO VIE
18:44:07,962 INFO [STDOUT] Segolene
18:44:07,962 INFO [STDOUT] SupraCanon
18:44:07,962 INFO [STDOUT] silex
18:44:07,962 INFO [STDOUT] snake
18:44:07,962 INFO [STDOUT] soliton

最佳答案

您的“after”数组按字母顺序排序:

18:44:07,962 INFO  [STDOUT] After=========
18:44:07,962 INFO [STDOUT] SUMO VIE
18:44:07,962 INFO [STDOUT] Segolene
18:44:07,962 INFO [STDOUT] SupraCanon
18:44:07,962 INFO [STDOUT] silex
18:44:07,962 INFO [STDOUT] snake
18:44:07,962 INFO [STDOUT] soliton

只是大写字母优先。

编辑:如果您想要不区分大小写的排序,请使用:

theList.add("SUMO VIE");theList.add("soliton");
theList.add("snake");theList.add("supracanon");
Collections.sort(theList, String.CASE_INSENSITIVE_ORDER);

按照下面 Natix 的建议。

关于java - 无法对我的字符串 ArrayList 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11887681/

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