gpt4 book ai didi

不使用 element.hashCode() 的 java.util.Set 实现

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:30:21 27 4
gpt4 key购买 nike

是否有 java.util.Set 实现不调用插入元素的 hashCode() 方法?

我必须使用某些库的类,其 hashCode() 实现行为不正常:当调用此 hashCode() 方法时,它会发送一个 HTTP 请求。 ..... 因此,将该类的实例放入 HashSet 会导致触发 HTTP 请求。
我想将与此 hashCode() 方法的交互减少到最低限度。因此,我需要一个不利用其包含元素的 hashCode() 方法的 Set 实现。

最佳答案

查看 Object.hashCode() 的文档方法和Set界面。

使用 TreeSet < Comparable > :

import java.util.Set;
import java.util.TreeSet;

public class NoHashCode implements Comparable< NoHashCode >{

final int value;

public NoHashCode( int val ) {
this.value = val;
}

@Override public int hashCode() {
throw new IllegalStateException( "This method must not be called" );
}

@Override
public int compareTo( NoHashCode o ) {
return this.value - o.value;
}

public static void main( String[] args ) {
Set< NoHashCode > set = new TreeSet<>();
set.add( new NoHashCode( 1 ));
set.add( new NoHashCode( 2 ));
set.add( new NoHashCode( 3 ));
set.add( new NoHashCode( 1 )); // '1' is already in set
System.out.println( set.size());// print 3
}
}

使用 TreeSet < T >( comparator ) :

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class NoHashCode {

final int value;

public NoHashCode( int val ) {
this.value = val;
}

@Override public int hashCode() {
throw new IllegalStateException( "This method must not be called" );
}

public static void main( String[] args ) {
Set< NoHashCode > set = new TreeSet<>( new Comparator< NoHashCode >(){
@Override public int compare( NoHashCode left, NoHashCode right ) {
return left.value - right.value;
}});
set.add( new NoHashCode( 1 ));
set.add( new NoHashCode( 2 ));
set.add( new NoHashCode( 3 ));
set.add( new NoHashCode( 1 )); // '1' is already in set
System.out.println( set.size());// print 3
}
}

关于不使用 element.hashCode() 的 java.util.Set 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15046210/

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