When should I use == and when should I use Equals?

博客主要探讨了 == 和 Equals 的使用场景。== 是可被类重载的运算符,通常用于比较引用是否指向同一对象;Equals 是虚方法,可被类重写。对于引用类型,多数情况用 Equals 测试相等性;对于值类型,用 == 代码更易读。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

When should I use == and when should I use Equals?

The Equals method is just a virtual one defined in System.Object, and overridden by whichever classes choose to do so. The == operator is an operator which can be overloaded by classes, but which usually has identity behaviour.

For reference types where == has not been overloaded, it compares whether two references refer to the same object - which is exactly what the implementation of Equals does in System.Object.

Value types do not provide an overload for == by default. However, most of the value types provided by the framework provide their own overload. The default implementation of Equals for a value type is provided by ValueType, and uses reflection to make the comparison, which makes it significantly slower than a type-specific implementation normally would be. This implementation also calls Equals on pairs of references within the two values being compared.

However, the main difference between the two types of comparison in normal use (where you're unlikely to be defining your own value types very often) is polymorphism. Operators are overloaded, not overridden, which means that unless the compiler knows to call the more specific version, it'll just call the identity version.

So, when should you use which operator? My rule of thumb is that for almost all reference types, use Equals when you want to test equality rather than reference identity. The exception is for strings - comparing strings with == does make things an awful lot simpler and more readable but you need to remember that both sides of the operator must be expressions of type string in order to get the comparison to work properly.

For value types, I'd normally use == for easier-to-read code. Things would get tricky if a value type provided an overload for == which acted differently to Equals, but I'd consider such a type very badly designed to start with.

/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.myapplication.embedding import androidx.window.embedding.EmbeddingAspectRatio import androidx.window.embedding.SplitAttributes import androidx.window.embedding.SplitPairFilter import androidx.window.embedding.SplitRule import androidx.annotation.IntRange import androidx.window.embedding.SplitRule.Companion.SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT import androidx.window.embedding.SplitRule.Companion.SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT import androidx.window.embedding.SplitRule.Companion.SPLIT_MIN_DIMENSION_ALWAYS_ALLOW import androidx.window.embedding.SplitRule.Companion.SPLIT_MIN_DIMENSION_DP_DEFAULT import androidx.window.embedding.SplitRule.FinishBehavior.Companion.ALWAYS import androidx.window.embedding.SplitRule.FinishBehavior.Companion.NEVER /** * Split configuration rules for activity pairs. Define when activities that were launched on top * should be placed adjacent to the one below, and the visual properties of such splits. Can be set * either by [RuleController.setRules] or [RuleController.addRule]. The rules are always * applied only to activities that will be started from the activity fills the whole parent task * container or activity in the primary split after the rules were set. */ class SplitPairRule internal constructor( /** * Filters used to choose when to apply this rule. The rule may be used if any one of the * provided filters matches. */ val filters: Set<SplitPairFilter>, defaultSplitAttributes: SplitAttributes, tag: String? = null, /** * Determines what happens with the primary container when all activities are finished in the * associated secondary container. * * @see SplitRule.FinishBehavior.NEVER * @see SplitRule.FinishBehavior.ALWAYS * @see SplitRule.FinishBehavior.ADJACENT */ val finishPrimaryWithSecondary: FinishBehavior = NEVER, /** * Determines what happens with the secondary container when all activities are finished in the * associated primary container. * * @see SplitRule.FinishBehavior.NEVER * @see SplitRule.FinishBehavior.ALWAYS * @see SplitRule.FinishBehavior.ADJACENT */ val finishSecondaryWithPrimary: FinishBehavior = ALWAYS, /** * If there is an existing split with the same primary container, indicates whether the * existing secondary container on top and all activities in it should be destroyed when a new * split is created using this rule. Otherwise the new secondary will appear on top by default. */ val clearTop: Boolean = false, @IntRange(from = 0) minWidthDp: Int = SPLIT_MIN_DIMENSION_DP_DEFAULT, @IntRange(from = 0) minHeightDp: Int = SPLIT_MIN_DIMENSION_DP_DEFAULT, @IntRange(from = 0) minSmallestWidthDp: Int = SPLIT_MIN_DIMENSION_DP_DEFAULT, maxAspectRatioInPortrait: EmbeddingAspectRatio = SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT, maxAspectRatioInLandscape: EmbeddingAspectRatio = SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT ) : SplitRule( tag, minWidthDp, minHeightDp, minSmallestWidthDp, maxAspectRatioInPortrait, maxAspectRatioInLandscape, defaultSplitAttributes ) { /** * Builder for [SplitPairRule]. * * @param filters Filters used to choose when to apply this rule. The rule may be used if any * one of the provided filters matches. */ class Builder( private val filters: Set<SplitPairFilter> ) { private var tag: String? = null @IntRange(from = 0) private var minWidthDp = SPLIT_MIN_DIMENSION_DP_DEFAULT @IntRange(from = 0) private var minHeightDp = SPLIT_MIN_DIMENSION_DP_DEFAULT @IntRange(from = 0) private var minSmallestWidthDp = SPLIT_MIN_DIMENSION_DP_DEFAULT private var maxAspectRatioInPortrait = SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT private var maxAspectRatioInLandscape = SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT private var finishPrimaryWithSecondary = NEVER private var finishSecondaryWithPrimary = ALWAYS private var clearTop = false private var defaultSplitAttributes = SplitAttributes.Builder().build() /** * Sets the smallest value of width of the parent window when the split should be used, in * DP. * When the window size is smaller than requested here, activities in the secondary * container will be stacked on top of the activities in the primary one, completely * overlapping them. * * The default is [SPLIT_MIN_DIMENSION_DP_DEFAULT] if the app doesn't set. * [SPLIT_MIN_DIMENSION_ALWAYS_ALLOW] means to always allow split. * * @param minWidthDp the smallest value of width of the parent window when the split should * be used, in DP. */ fun setMinWidthDp(@IntRange(from = 0) minWidthDp: Int): Builder = apply { this.minWidthDp = minWidthDp } /** * Sets the smallest value of height of the parent task window when the split should be * used, in DP. When the window size is smaller than requested here, activities in the * secondary container will be stacked on top of the activities in the primary one, * completely overlapping them. * * It is useful if it's necessary to split the parent window horizontally for this * [SplitPairRule]. * * The default is [SPLIT_MIN_DIMENSION_DP_DEFAULT] if the app doesn't set. * [SPLIT_MIN_DIMENSION_ALWAYS_ALLOW] means to always allow split. * * @param minHeightDp the smallest value of height of the parent task window when the split * should be used, in DP. * * @see SplitAttributes.LayoutDirection.TOP_TO_BOTTOM * @see SplitAttributes.LayoutDirection.BOTTOM_TO_TOP */ fun setMinHeightDp(@IntRange(from = 0) minHeightDp: Int): Builder = apply { this.minHeightDp = minHeightDp } /** * Sets the smallest value of the smallest possible width of the parent window in any * rotation when the split should be used, in DP. When the window size is smaller than * requested here, activities in the secondary container will be stacked on top of the * activities in the primary one, completely overlapping them. * * The default is [SPLIT_MIN_DIMENSION_DP_DEFAULT] if the app doesn't set. * [SPLIT_MIN_DIMENSION_ALWAYS_ALLOW] means to always allow split. * * @param minSmallestWidthDp the smallest value of the smallest possible width of the parent * window in any rotation when the split should be used, in DP. */ fun setMinSmallestWidthDp(@IntRange(from = 0) minSmallestWidthDp: Int): Builder = apply { this.minSmallestWidthDp = minSmallestWidthDp } /** * Sets the largest value of the aspect ratio, expressed as `height / width` in decimal * form, of the parent window bounds in portrait when the split should be used. When the * window aspect ratio is greater than requested here, activities in the secondary container * will be stacked on top of the activities in the primary one, completely overlapping them. * * This value is only used when the parent window is in portrait (height >= width). * * The default is [SPLIT_MAX_ASPECT_RATIO_PORTRAIT_DEFAULT] if the app doesn't set, which is * the recommend value to only allow split when the parent window is not too stretched in * portrait. * * @param aspectRatio the largest value of the aspect ratio, expressed as `height / width` * in decimal form, of the parent window bounds in portrait when the split should be used. * * @see EmbeddingAspectRatio.ratio * @see EmbeddingAspectRatio.ALWAYS_ALLOW * @see EmbeddingAspectRatio.ALWAYS_DISALLOW */ fun setMaxAspectRatioInPortrait(aspectRatio: EmbeddingAspectRatio): Builder = apply { this.maxAspectRatioInPortrait = aspectRatio } /** * Sets the largest value of the aspect ratio, expressed as `width / height` in decimal * form, of the parent window bounds in landscape when the split should be used. When the * window aspect ratio is greater than requested here, activities in the secondary container * will be stacked on top of the activities in the primary one, completely overlapping them. * * This value is only used when the parent window is in landscape (width > height). * * The default is [SPLIT_MAX_ASPECT_RATIO_LANDSCAPE_DEFAULT] if the app doesn't set, which * is the recommend value to always allow split when the parent window is in landscape. * * @param aspectRatio the largest value of the aspect ratio, expressed as `width / height` * in decimal form, of the parent window bounds in landscape when the split should be used. * * @see EmbeddingAspectRatio.ratio * @see EmbeddingAspectRatio.ALWAYS_ALLOW * @see EmbeddingAspectRatio.ALWAYS_DISALLOW */ fun setMaxAspectRatioInLandscape(aspectRatio: EmbeddingAspectRatio): Builder = apply { this.maxAspectRatioInLandscape = aspectRatio } /** * Sets the behavior of the primary container when all activities are finished in the * associated secondary container. * * @param finishPrimaryWithSecondary the [SplitRule.FinishBehavior] of the primary container * when all activities are finished in the associated secondary container. * * @see SplitRule.FinishBehavior.NEVER * @see SplitRule.FinishBehavior.ALWAYS * @see SplitRule.FinishBehavior.ADJACENT */ fun setFinishPrimaryWithSecondary( finishPrimaryWithSecondary: FinishBehavior ): Builder = apply { this.finishPrimaryWithSecondary = finishPrimaryWithSecondary } /** * Sets the behavior of the secondary container when all activities are finished in the * associated primary container. * * @param finishSecondaryWithPrimary the [SplitRule.FinishBehavior] of the secondary * container when all activities are finished in the associated primary container. * * @see SplitRule.FinishBehavior.NEVER * @see SplitRule.FinishBehavior.ALWAYS * @see SplitRule.FinishBehavior.ADJACENT */ fun setFinishSecondaryWithPrimary( finishSecondaryWithPrimary: FinishBehavior ): Builder = apply { this.finishSecondaryWithPrimary = finishSecondaryWithPrimary } /** * Sets whether the existing secondary container on top and all activities in it should be * destroyed when a new split is created using this rule. Otherwise the new secondary will * appear on top by default. * * @param clearTop whether the existing secondary container on top and all activities in it * should be destroyed when a new split is created using this rule. */ @SuppressWarnings("MissingGetterMatchingBuilder") fun setClearTop(clearTop: Boolean): Builder = apply { this.clearTop = clearTop } /** * Sets the default [SplitAttributes] to apply on the activity containers pair when the host * task bounds satisfy [minWidthDp], [minHeightDp], [minSmallestWidthDp], * [maxAspectRatioInPortrait] and [maxAspectRatioInLandscape] requirements. * * @param defaultSplitAttributes the default [SplitAttributes] to apply on the activity * containers pair when the host task bounds satisfy all the rule requirements. */ fun setDefaultSplitAttributes(defaultSplitAttributes: SplitAttributes): Builder = apply { this.defaultSplitAttributes = defaultSplitAttributes } /** * Sets a unique string to identify this [SplitPairRule], which defaults to `null`. * The suggested usage is to set the tag to be able to differentiate between different rules * in the [SplitAttributesCalculatorParams.splitRuleTag]. * * @param tag unique string to identify this [SplitPairRule]. */ fun setTag(tag: String?): Builder = apply { this.tag = tag } /** * Builds a `SplitPairRule` instance. * * @return The new `SplitPairRule` instance. */ fun build() = SplitPairRule( filters, defaultSplitAttributes, tag, finishPrimaryWithSecondary, finishSecondaryWithPrimary, clearTop, minWidthDp, minHeightDp, minSmallestWidthDp, maxAspectRatioInPortrait, maxAspectRatioInLandscape, ) } /** * Creates a new immutable instance by adding a filter to the set. * @see filters */ internal operator fun plus(filter: SplitPairFilter): SplitPairRule { val newSet = mutableSetOf<SplitPairFilter>() newSet.addAll(filters) newSet.add(filter) return Builder(newSet.toSet()) .setTag(tag) .setMinWidthDp(minWidthDp) .setMinHeightDp(minHeightDp) .setMinSmallestWidthDp(minSmallestWidthDp) .setMaxAspectRatioInPortrait(maxAspectRatioInPortrait) .setMaxAspectRatioInLandscape(maxAspectRatioInLandscape) .setFinishPrimaryWithSecondary(finishPrimaryWithSecondary) .setFinishSecondaryWithPrimary(finishSecondaryWithPrimary) .setClearTop(clearTop) .setDefaultSplitAttributes(defaultSplitAttributes) .build() } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SplitPairRule) return false if (!super.equals(other)) return false if (filters != other.filters) return false if (finishPrimaryWithSecondary != other.finishPrimaryWithSecondary) return false if (finishSecondaryWithPrimary != other.finishSecondaryWithPrimary) return false if (clearTop != other.clearTop) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + filters.hashCode() result = 31 * result + finishPrimaryWithSecondary.hashCode() result = 31 * result + finishSecondaryWithPrimary.hashCode() result = 31 * result + clearTop.hashCode() return result } override fun toString(): String = "${SplitPairRule::class.java.simpleName}{" + "tag=$tag" + ", defaultSplitAttributes=$defaultSplitAttributes" + ", minWidthDp=$minWidthDp" + ", minHeightDp=$minHeightDp" + ", minSmallestWidthDp=$minSmallestWidthDp" + ", maxAspectRatioInPortrait=$maxAspectRatioInPortrait" + ", maxAspectRatioInLandscape=$maxAspectRatioInLandscape" + ", clearTop=$clearTop" + ", finishPrimaryWithSecondary=$finishPrimaryWithSecondary" + ", finishSecondaryWithPrimary=$finishSecondaryWithPrimary" + ", filters=$filters" + "}" } 将这个kotlin文件转为java文件
08-12
资源下载链接为: https://pan.quark.cn/s/140386800631 通用大模型文本分类实践的基本原理是,借助大模型自身较强的理解和推理能力,在使用时需在prompt中明确分类任务目标,并详细解释每个类目概念,尤其要突出类目间的差别。 结合in-context learning思想,有效的prompt应包含分类任务介绍及细节、类目概念解释、每个类目对应的例子和待分类文本。但实际应用中,类目和样本较多易导致prompt过长,影响大模型推理效果,因此可先通过向量检索缩小范围,再由大模型做最终决策。 具体方案为:离线时提前配置好每个类目的概念及对应样本;在线时先对给定query进行向量召回,再将召回结果交给大模型决策。 该方法不更新任何模型参数,直接使用开源模型参数。其架构参考GPT-RE并结合相关实践改写,加入上下文学习以提高准确度,还使用BGE作为向量模型,K-BERT提取文本关键词,拼接召回的相似例子作为上下文输入大模型。 代码实现上,大模型用Qwen2-7B-Instruct,Embedding采用bge-base-zh-v1.5,向量库选择milvus。分类主函数的作用是在向量库中召回相似案例,拼接prompt后输入大模型。 结果方面,使用ICL时accuracy达0.94,比bert文本分类的0.98低0.04,错误类别6个,处理时添加“家居”类别,影响不大;不使用ICL时accuracy为0.88,错误58项,可能与未修改prompt有关。 优点是无需训练即可有较好结果,例子优质、类目界限清晰时效果更佳,适合围绕通用大模型api打造工具;缺点是上限不高,仅针对一个分类任务部署大模型不划算,推理速度慢,icl的token使用多,用收费api会有额外开销。 后续可优化的点是利用key-bert提取的关键词,因为核心词语有时比语意更重要。 参考资料包括
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值