在 ArrayList 中计数

编程入门 行业动态 更新时间:2024-10-21 19:28:19
本文介绍了在 ArrayList 中计数 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

更新代码

我正在尝试找出一种方法来计算一个值在 ArrayList 中出现的频率.

I'm trying to figure out a way to count how often one value appears in an ArrayList.

System.out.println("Hand 1, Number of Clubs: " 
              + hands[0].frequency(hands[0], Card.Suit.CLUBS));

所以在上面的例子中,我想计算手上有多少俱乐部"[0].

So in the above case i want to count how many "Clubs" are in hands[0].

public int frequency(Hand c, Suit suit){
    int count = 0;
    if(suit == suit) //need this to be "If suit (club) is present, count++)
            {
             count++;
            }    
    return count;
}

我正在画一个空白....如果我将方法类型更改为 ArrayList 那么我将无法返回count"

I'm drawing a blank.... If i change the method type to ArrayList then i cannot return "count"

hands[0] 创建者:

hands[0] is created by:

    Hand[] hands = new Hand[4];
    for(int i=0; i<hands.length; i++) {
       hands[i]=new Hand();
       }
       for(int i=0; i<=Deck.size()+8; i++) {
          for(Hand hand:hands) {
             hand.addSingleCard(Deck.deal());
           }
       }

推荐答案

Collections.frequency

您已经可以从 Collections 类,位于 frequency 方法.

public static int frequency(Collection<?> c, Object o)

这将返回特定对象在集合中出现的次数.

That will return the number of occurrences of a specific object inside a collection.

请注意,不提供有效的 equals 方法这行不通,或者至少不能处理您心目中的相等性,因为 Java 可以不知道你说的平等是什么意思.

Mind that without providing a vaild equals method this won't work or at least won't work with the equality you have in mind, since Java does't know your meaning of equality.

这篇关于在 ArrayList 中计数 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 10:22:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/884961.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ArrayList

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!