【问题标题】:Passing same value to a method and make it return true the first time and false the second time将相同的值传递给方法并使其第一次返回true,第二次返回false
【发布时间】:2021-06-03 07:53:54
【问题描述】:

是否可以将值传递给方法并声明它是唯一的?因此,我们第一次传递值时,它返回 true 并保留该值,下一次返回 false 时,它​​会检查它是否已经传递过一次。有什么代码可以让它工作吗?

public class Main {

    public static void main(String[] args){
        Main bb = new Main();

        String a1 = 3000;
        String a2 = 3000;

        boolean output3 = bb.addAccount(a1);
        assertEquals(true, output3);
        
        boolean output4 = bb.addAccount(a2);
        assertEquals(false, output4);
    }

    public boolean addAccount(String acc) {
        int store = 0;
        boolean out = false;
        if (acc == 3000 && store = 0){
            out = true;
            store = 1;
        }
        else if (acc == 300 && store != 0){
            out = false;
        }
        return out;
    }
}

【问题讨论】:

  • String a1 = 3000;
  • 您需要向您的类添加一些数据结构,以保存已传递给该方法的所有值。您是否使用数组、列表、集合或其他东西取决于您。然后当你的方法被调用时,检查传递的值是否已经是你的数组/列表的一部分,如果它返回 false。否则将其添加到您的列表/数组中并返回 true。

标签: java methods boolean


【解决方案1】:
// a class field
Set<String> seen = new HashSet<>();

// a set will return false when adding an existing value
// and return true otherwise. Since sets will not contain
// duplicates adding will not add additional values.
public boolean addAccount(String acc) {
    return seen.add(acc);   
}

如果这就是你想做的全部,你不需要方法。如果方法中有更多处理,则仍然使用集合,进行处理,并返回适当的布尔值。

【讨论】:

  • 谢谢。那行得通。所以 Hashset 允许重复值,但不允许重复键。这非常有用。
  • 不完全。 HashSet 不允许重复,句号。您对 HashMap 感到困惑,它允许重复值但不允许重复键。还要记住 set 使用哈希来查找值,因此包含的效率是 O(1),而不是必须遍历列表并且是 O(n) 的列表。
  • 好的。所以这就是hashmap ...这是hashset。所以既不重复键也不重复值。谢谢你的解释。 :)
  • hashSet 中没有valueskeys。它只是一组对象。 Set.of(1,2,3,4) 是一组 4 个整数。
猜你喜欢
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-29
相关资源
最近更新 更多