“==” vs “equals ” & “isBlank ” vs “ isEmpty”

本文深入探讨了Java中==运算符与equals方法的区别,特别是在字符串比较中的应用,并对比了StringUtils的isBlank与isEmpty方法在空字符串判断上的差异。
1." == " vs " equals "

基本类型:" == " 比较的是值是否相等
引用类型:" == " 比较的是两者在内存中存放的地址(堆内存地址)

引用类型:默认情况下,对比它们的地址是否相等;如果equals()方法被重写,则根据重写过程来比较(String类中比较数据值)。

public class EqualsTest {
    public static void main(String[] args) {

        String s1 = new String("aa");
        String s2 = "aa";
        String s3 = s1;
        String s4 = new String("aa");

        System.out.println(s1 == s2);//false
        System.out.println(s1.equals(s2));//true

        System.out.println(s1 == s3);//true
        System.out.println(s1.equals(s3));//true

        System.out.println(s1 == s4);//false
        System.out.println(s1.equals(s4));//true

    }
}

equals源码:

//Object类
 public boolean equals(Object obj) {
        return (this == obj);
    }
//String类 重写
  public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }
2." StringUtils.isBlank() " vs " StringUtils.isEmpty() "

(注:此处的StringUtils的全类名为org.apache.commons.lang3.StringUtils,使用需导入commons-lang3-xx.jar包)
empty认为空格也是有内容的,所以空格不判定为空;blank则反之

StringUtils.isEmpty(" ");//false
StringUtils.isEmpty("");//true

StringUtils.isBlank(" ");//true
StringUtils.isBlank("");//true
* @see Observe */ public static RequestExecuteMetadata createRequest(@NotNull Method method, @Nullable Object[] args) { Request<?> request = null; //create request. List<Callback> callbacks = new ArrayList<>(); //parameter callbacks. ThrowablePredicate throwablePredicate = null; AsyncPubSubExecutorProvider executorProvider = null; Executor subscriptionExecutor = null; Executor observeExecutor = null; Map<String, Pair<Boolean, Object>> setterMetadata = new HashMap<>(); //support setter data. /* * When the parameter does not provide the type of Request, * find the annotation for the method. * */ if (args == null) { RequestType requestType = method.getAnnotation(RequestType.class); if (requestType == null) { throw new UnknownRequestParameterException(); } request = ReflectUtil.instantiates(requestType.value()); } else { //First, filter to see if there are any Request instances. List<Object> requestInstances = Arrays.stream(args) .filter(r -> r instanceof Request).collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(requestInstances)) { if (requestInstances.size() > 1) throw new UnknownRequestParameterException(); //Only one request can exist. request = (Request<?>) requestInstances.get(0); } //the reflection creation type when there is no request for the parameter. Class<? extends Request> requestType = null; //support for RequestConstructor annotation as constructor args. //Arrange the construction parameter groups in the order provided by the annotations. SortedMap<Integer, Object> constructorArgs = null; if (request == null) constructorArgs = new TreeMap<>();//Initialize only when no instance exists. Parameter[] parameters = method.getParameters(); for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg == null) continue; // null filter continue. if (arg instanceof Request) continue;//It has been resolved in the above steps. /* * Support type 1: Retrieve the type of Request from a specific interface * and support subsequent parsing. */ if (arg instanceof RequestTypeSupplier && request == null) { Class<? extends Request> rt = ((RequestTypeSupplier) arg).getRequestType(); if (requestType == null) { requestType = rt; } else { if (!Objects.equals(requestType, rt)) { throw new UnknownRequestParameterException(); } } } Parameter parameter = parameters[i]; /* * Support type 2: Callback type parameter parsing, supporting object instance, * collection, array and other types for subsequent parsing. */ if (arg instanceof Callback) { callbacks.add((Callback) arg); } else if (arg instanceof Collection) { //2-arg-collection-1: all of them are Callback elements. if (((Collection<?>) arg).stream().allMatch(c -> c instanceof Callback)) { callbacks.addAll((Collection<? extends Callback>) arg); } } else if (arg.getClass().isArray()) { //2-arg-array-1: all of them are Callback elements. if (Callback.class.isAssignableFrom(arg.getClass().getComponentType())) { for (Object o : ArrayUtils.toArray(arg)) { callbacks.add((Callback) o); } } } /* * Support type 3: Support annotation RequestConstructor parsing, provided that * the parameter array does not have a Request instance. */ if (request == null && parameter.isAnnotationPresent(RequestConstructor.class)) { RequestConstructor requestConstructor = parameter.getAnnotation(RequestConstructor.class); if (requestConstructor.required()) { constructorArgs.put(requestConstructor.order(), arg); } } /* * Support type 4:Support annotation RequestSetter parsing, perform set related * assignment after obtaining the Request instance. */ if (parameter.isAnnotationPresent(RequestSetter.class)) { RequestSetter requestSetter = parameter.getAnnotation(RequestSetter.class); String name = requestSetter.name(); if (StringUtils.isBlank(name)) name = parameter.getName(); setterMetadata.put(name, Pair.create(requestSetter.useReflect(), arg)); } /* * Support type 5:Support parsing the first {@code ThrowablePredicate} instance * object from parameters. */ if (throwablePredicate == null && arg instanceof ThrowablePredicate) { throwablePredicate = (ThrowablePredicate) arg; } /* * Support type 6:Support parsing the first {@code AsyncPubSubExecutorProvider} instance * object from the parameters, or the subscriber {@code Executor} instance object marked * with annotation {@code Subscription}, or the observer {@code Executor} instance object * marked with annotation {@code Observe}. */ if (executorProvider == null && arg instanceof AsyncPubSubExecutorProvider) { executorProvider = (AsyncPubSubExecutorProvider) arg; } if (executorProvider == null && (subscriptionExecutor == null || observeExecutor == null) && arg instanceof Executor) { if (parameter.isAnnotationPresent(Subscription.class)) { subscriptionExecutor = (Executor) arg; } else if (parameter.isAnnotationPresent(Observe.class)) { observeExecutor = (Executor) arg; } } } //After the loop ends, initialize using the type based on whether // the request instance exists. if (request == null) { if (requestType == null) { RequestType annotation = method.getAnnotation(RequestType.class); if (annotation == null) { throw new UnknownRequestParameterException(); } requestType = annotation.value(); } if (constructorArgs.isEmpty()) { request = ReflectUtil.instantiates(requestType); } else { request = ReflectUtil.instantiates(requestType, constructorArgs.values().toArray()); } } } //Finally, perform set support assignment on the instantiated request instance. if (!setterMetadata.isEmpty()) { for (Map.Entry<String, Pair<Boolean, Object>> entry : setterMetadata.entrySet()) { String name = entry.getKey(); Pair<Boolean, Object> assignmentInfo = entry.getValue(); Object value = assignmentInfo.getSecond(); if (assignmentInfo.getFirst()) { ReflectUtil.setFieldValue(request, name, value); } else { executeSetMethod(request, request.getClass(), name, value); } } } return new ParameterResolveRequestExecuteMetadata(request, method, callbacks, throwablePredicate, executorProvider != null ? executorProvider : (subscriptionExecutor != null || observeExecutor != null) ? new AsyncPubSubExecutorProviderImpl(subscriptionExecutor, observeExecutor) : null); } 你觉得写的怎么样? 是否可以优化?
11-21
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值