Using arrays to implement caching examples

Source: Internet
Author: User
public class cachefinal{private final String name;
	private static cachefinal[] cache = new CACHEFINAL[10];
	
	Record cache instance at cache location, Cache[p-1] is the most recent cache instance private static int p = 0;
	The public cachefinal (String name) {//whether the constructor is hidden depends on the system needing this.name = name;
	Public String GetName () {return name;
			public static cachefinal valueof (String name) {//Traversal of objects already cached for (int i =0; i<p;i++) {//If you already have the same instance, return the cached instance directly
			if (Cache[i]!= null && cache[i].getname (). Equals (name)) {return cache[i];
			}///If the cache is full with the IF (p==10) {//Overwrite first object cache[0] = new Cachefinal (name);
			Set p to 1 p=1;
		return cache[0]; 
			}else{//cache the newly created object, p plus 1 cache[p++] = new Cachefinal (name);
		return cache[p-1]; }//equals method public boolean equals (Object obj) {if (obj instanceof cachefinal) {cachefinal CF = (
			
				cachefinal) obj;
				if (Name.equals (Cf.getname ()) {return true;
	return false; //hashcode method public int hashcode () {RETUrn Name.hashcode ();
		public static void Main (string[] args) {cachefinal C1 = cachefinal.valueof ("Hello");
		
		cachefinal C2 = cachefinal.valueof ("Hello");
		
		Whether the comparison is a reference to the same object System.out.println (c1 = = C2);
 }
	
	
}

Java.lang.Integer class, this caching processing policy is used, and if you create an integer object with the new constructor class, you return a new integer to the
image at a time, If you use the ValueOf method to create an integer object, the object created by the method is cached.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.