gpt4 book ai didi

java - 如何使用整理器对MutableList 进行排序?

转载 作者:行者123 更新时间:2023-12-02 12:49:36 25 4
gpt4 key购买 nike

我想使用listFiles()Collator.getInstance(Locale.ENGLISH)的输出进行排序。
我该怎么做?

    val path = File(Os.getenv("EXTERNAL_STORAGE"))
val filefilter = FileFilter { file -> file.isDirectory && !file.isHidden }
val fileList = path.listFiles(filefilter)!!.toList()
Collections.sort(fileList, Collator.getInstance(Locale.ENGLISH))
我得到的错误是
java.lang.ExceptionInInitializerError
at com.praps.myapplication.ui.list.ListFragment.onCreateView(ListFragment.kt:43)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2224)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1997)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:221)
at android.app.ActivityThread.main(ActivityThread.java:7520)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.ClassCastException: java.io.File cannot be cast to java.lang.String
at java.text.Collator.compare(Collator.java:277)
at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)
at java.util.TimSort.sort(TimSort.java:220)
at java.util.Arrays.sort(Arrays.java:1492)
at java.util.ArrayList.sort(ArrayList.java:1470)
at java.util.Collections.sort(Collections.java:206)
at com.praps.myapplication.ui.list.dummy.DummyContent

最佳答案

您正在尝试使用Array<File>Comparator<String>进行排序,这就是原因。没有类型警告,因为Collator实际上是Comparator<Any>,但是它的实现RuleBasedCollator不是,它仅比较字符串。
您需要制作一个中间比较器,该中间比较器使用文件名并进行比较:

val files = dir.listFiles().orEmpty()
val collator = Collator.getInstance(Locale.ENGLISH);
files.sortWith { a, b -> collator.compare(a.name, b.name) }

关于java - 如何使用整理器对MutableList <File>进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64146025/

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