Dab tsi yog kev siv overriding sib npaug txoj kev hauv Java?
Dab tsi yog kev siv overriding sib npaug txoj kev hauv Java?

Video: Dab tsi yog kev siv overriding sib npaug txoj kev hauv Java?

Video: Dab tsi yog kev siv overriding sib npaug txoj kev hauv Java?
Video: tu txiv tsi pab nkauj tawm tshiab-Cover(niam vamkhwb&paj yeeb& xis xyooj&ntxawm xyooj&niam npawglem) 2024, Hlis ntuj nqeg
Anonim

Override sib npaug thiab hashCode hauv Java

sib npaug () txoj kev yog siv los sib piv Cov Khoom rau kev sib npaug thaum hashCode yog siv tsim kom muaj tus lej lej sib raug rau cov khoom ntawd

Ntawm no, dab tsi yog siv txoj kev sib npaug hauv Java?

Cov sib npaug () txoj kev piv ob yam khoom rau kev sib npaug thiab rov qab muaj tseeb yog tias lawv yog sib npaug . Cov sib npaug () txoj kev muaj nyob rau hauv Object class siv tus neeg siv tus kheej (==) los txiav txim seb ob yam khoom puas yog sib npaug . Rau hom ntaub ntawv qub, qhov no muab qhov tseeb.

Tsis tas li ntawd, yuav ua li cas koj hla txoj kev sib npaug hauv Java? Nyob rau hauv saum toj no daim code class Person muaj ib tug overridden equals() txoj kev, uas coj cov nram qab no kauj ruam-los-kauj ruam mus kom ze:

  1. Yog hais tias qhov kev siv rau cov khoom no yog tib yam li qhov kev siv rau qhov kev sib cav, rov qab muaj tseeb.
  2. Yog hais tias qhov kev sib cav yog null, rov qab tsis tseeb.
  3. Yog tias cov khoom tsis yog los ntawm tib chav kawm, rov qab tsis raug.

Yog li ntawd, vim li cas peb thiaj li yuav tsum tau hla txoj kev sib npaug hauv Java?

Txoj hlua class overrides tus sib npaug txoj kev nws tau txais los ntawm Object class thiab siv logic los sib piv ob txoj hlua khoom cim los ntawm tus cwj pwm. Yog vim li cas sib npaug txoj kev nyob rau hauv Object chav kawm siv qhov sib npaug yog vim nws tsis paub yuav ua li cas lwm yam.

Dab tsi yog kev siv overriding hashCode thiab sib npaug hauv Java?

yog ib chav kawm overrides sib npaug , nws yuav tsum override hashCode . thaum lawv ob leeg hla dhau , sib npaug thiab hashCode yuav tsum siv tib txheej teb. yog tias ob yam khoom sib npaug , ces lawv hashCode tus nqi yuav tsum yog sib npaug ib yam nkaus. yog hais tias cov khoom yog immutable, ces hashCode yog tus neeg sib tw rau caching thiab tub nkeeg pib.

Pom zoo: