首页 \ 问答 \ Java - 重写hashCode和toString(Java - Overriding hashCode and toString)

Java - 重写hashCode和toString(Java - Overriding hashCode and toString)

当两个对象在等级A中具有相同的ele值时,那么这两个对象是相等的。 所以我重写了toString和hashCode来返回对象的ele (不考虑s的值)。

public class A {
    private int ele;
    private String s;

    public int getEle() {
        return ele;
    }

    public void setEle(int ele) {
        this.ele = ele;
    }

    public String getS() {
        return s;
    }

    public void setS(String s) {
        this.s = s;
    }

    @Override
    public int hashCode(){
        return ele;
    }

    @Override
    public String toString() {
        return String.valueOf(ele);
    }
}

public static void main(String[] args) {

    Map<A, String> map = new HashMap<>();
    A a1 = new A();
    a1.setEle(10);
    a1.setS("abc");

    A a2 = new A();
    a2.setEle(10);
    a2.setS("efg");

    map.put(a1, "val1");
    map.put(a2, "val2");

    System.out.println(map.get(a1));
    System.out.println(map.get(a2));

}

输出:

val1
val2

但是,如果我将a1a2值放在地图中,我期望map.get(a1) map.get(a2) map.get(a1)map.get(a2) map.get(a1)都返回val1val2


When two objects have same value of ele in class A then those two objects are equal. So I have overridden toString and hashCode to return the object's ele (not considering the value of s anywhere).

public class A {
    private int ele;
    private String s;

    public int getEle() {
        return ele;
    }

    public void setEle(int ele) {
        this.ele = ele;
    }

    public String getS() {
        return s;
    }

    public void setS(String s) {
        this.s = s;
    }

    @Override
    public int hashCode(){
        return ele;
    }

    @Override
    public String toString() {
        return String.valueOf(ele);
    }
}

public static void main(String[] args) {

    Map<A, String> map = new HashMap<>();
    A a1 = new A();
    a1.setEle(10);
    a1.setS("abc");

    A a2 = new A();
    a2.setEle(10);
    a2.setS("efg");

    map.put(a1, "val1");
    map.put(a2, "val2");

    System.out.println(map.get(a1));
    System.out.println(map.get(a2));

}

Output:

val1
val2

But if I put value of a1 and a2 in a map, I was expecting either val1 or val2 to be returned for both map.get(a1) and map.get(a2).


原文:https://stackoverflow.com/questions/36290579
更新时间:2022-11-11 07:11

最满意答案

它被称为砰操作员。

这意味着,使用这种类型的默认属性。

https://stackoverflow.com/questions/1845646/vb-net-doesnt-anyone-use-the-dictionary-member-access-expression-aka-the-b


Its called the Bang Operator.

It means, use the default property of this type.

It was very common in VB6 code, used to access the fields of a Recordset and avoid trouble with field names that were also a keyword. An alternative to the dot operator and [brackets]. The bang still works:

value = row!column1

instead of

value = row("column1")

Consider it a typing aid, use at your discretion.

相关问答

更多
  • 它被称为砰操作员。 这意味着,使用这种类型的默认属性。 https://stackoverflow.com/questions/1845646/vb-net-doesnt-anyone-use-the-dictionary-member-access-expression-aka-the-b Its called the Bang Operator. It means, use the default property of this type. It was very common in VB6 code ...
  • 不, sampleArray并不真正指向数组的第一个元素。 sampleArray 是数组。 出现混淆的原因是,在使用sampleArray大多数地方,它将被指向数组的第一个元素的指针替换。 “大多数地方”的意思是“任何地方,它不是sizeof或一元&操作符的操作数”。 由于sampleArray是数组本身,并且作为一元操作数( &是它维护个性的地方之一,这意味着&sampleArray是指向整个数组的指针。 No, sampleArray does not really point to the firs ...
  • 用于应用程序执行控制的一组页面。 PageSet管理,存储,匹配和执行Pages。 这就是我能在这个词上找到的全部内容。 基本上如果说你有一个博客,你可以有一个用于修改条目的页面集,如添加,编辑,删除。 这些操作中的每一个都将具有不同的页面和控件来运行该操作。 页面集将是那些组。 A set of Pages used for application execution control. A PageSet manages, stores, matches and executes Pages. That ...
  • 在你的代码片段中, this(port, 50, null)表示对同一个类中的构造函数的显式调用,该构造函数有三个参数,其中两个参数传递硬编码参数( 50和null ) In your code snippet, this(port, 50, null) denotes an explicit call to a constructor in the same class, which has three parameters, for two of which you pass hardcoded arg ...
  • 它必须是if ((integer & 2) != 0) 。 Java不像C++那样将正整数识别为true ,将0识别为false 。 否则,它测试是否设置了右边的第二个位,即它是1。 It must be if ((integer & 2) != 0). Java does not recognize positive integers as true and 0 as false like in C++. Otherwise it tests if the second bit from the righ ...
  • 您可以在MSDN中看到“ String.IndexOf Method(String) ”。 You can see in MSDN, "String.IndexOf Method (String)".
  • 指向由&给出的internalIPItr->second.outboundPortIPs地址的指针将转换为void* 。 The pointer to the address of internalIPItr->second.outboundPortIPs, given by &, is converted to void*.
  • 你需要一个语言扩展甚至能够使用它,这是多么特别! 它没有做任何事情,它只是一个看起来很特别的角色,GHC人们喜欢用低级别的可能与拳击相关的东西。 有(# a, b #)这是a和b的未装箱元组的类型,这是你在那里看到的 - 它不是( #State# , ... ,它是(# State#, ... ...... You need a language extension to even be able to use it, that's how special it is! It doesn't do anyt ...
  • 用语言: 注释标志已设置( (?x) )。 字符串( ^ )的开头必须是第一个,后面必须跟( ?= )零个或多个字符( .* ),然后是( (||) )一个数字( \d ),一个标点符号( \p{P} )或符号( \p{S} )。 字符串开始后,必须有6个或更多字符( .{6,} ) 这解释了吗? In words: The comments flag is set ((?x)). The start of the string (^) must be first, which must be follow ...
  • 要知道它是哪个字符,请将光标放在^K并在正常模式下按g a 。 你可能会得到: <^K> 11, Hexa 0b, Octal 013 它有ascii代码11所以它可能是vertical tab 。 您可以使用此组合Ctrl-v + Ctrl-k创建它 To know which character it is, put the cursor on ^K and press ga in normal-mode. You will get probably: <^K> 11, Hexa 0b, ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)