[转载]Java数组扩容算法及Java对它的应用

简介: 原文链接:http://www.cnblogs.com/gw811/archive/2012/10/07/2714252.html Java数组扩容的原理   1)Java数组对象的大小是固定不变的,数组对象是不可扩容的。

原文链接:http://www.cnblogs.com/gw811/archive/2012/10/07/2714252.html

Java数组扩容的原理

  1)Java数组对象的大小是固定不变的,数组对象是不可扩容的。

  2)利用数组复制方法可以变通的实现数组扩容。

  3)System.arraycopy()可以复制数组。

  4)Arrays.copyOf()可以简便的创建数组副本。

  5)创建数组副本的同时将数组长度增加就变通的实现了数组的扩容。

 源码展示:

复制代码
 1 public class Arrays {
 2 /**  3  * @param original: the array to be copied  4  * @param newLength: the length of the copy to be returned  5  * @return a copy of the original array, truncated or padded with zeros  6  * to obtain the specified length  7 */  8 public static int[] copyOf(int[] original, int newLength) {  9 int[] copy = new int[newLength]; 10 System.arraycopy(original, 0, copy, 0, 11  Math.min(original.length, newLength)); 12 return copy; 13  } 14 /** 15  * @param original the array from which a range is to be copied 16  * @param from the initial index of the range to be copied, inclusive 17  * @param to the final index of the range to be copied, exclusive. 18  * (This index may lie outside the array.) 19  * @return a new array containing the specified range from the original array, 20  * truncated or padded with zeros to obtain the required length 21 */ 22 public static int[] copyOfRange(int[] original, int from, int to) { 23 int newLength = to - from; 24 if (newLength < 0) 25 throw new IllegalArgumentException(from + " > " + to); 26 int[] copy = new int[newLength]; 27 System.arraycopy(original, from, copy, 0, 28 Math.min(original.length - from, newLength)); 29 return copy; 30  } 31 }
复制代码

 示例说明:

复制代码
 1 import java.util.Arrays;
 2 
 3 /** 数组变长算法!  4  * 数组对象长度不可改变  5  * 但是很多实际应用需要长度可变的数组  6  * 可以采用复制为容量更大的新数组, 替换原数组, 实现变长操作  7  * */  8 public class ArrayExpand {  9 public static void main(String[] args) { 10 //数组变长(扩容)算法! 11 int[] ary={1,2,3}; 12 ary=Arrays.copyOf(ary, ary.length+1); 13 ary[ary.length-1]=4; 14 System.out.println(Arrays.toString(ary));//[1, 2, 3, 4] 15 //字符串连接原理 16 char[] chs = { '中', '国' }; 17 chs = Arrays.copyOf(chs, chs.length + 1); 18 chs[chs.length - 1] = '北'; 19 chs = Arrays.copyOf(chs, chs.length + 1); 20 chs[chs.length - 1] = '京'; 21 //字符数组按照字符串打印 22 System.out.println(chs);//中国北京 23 //其他数组按照对象打印 24 System.out.println(ary);//[I@4f1d0d 25  } 26 }
复制代码

 实现案例:

  案例1 : 统计一个字符在字符串中的所有位置.
  字符串: 统计一个字符在字符串中的所有位置
  字符: '字'
  返回: {4,7}

复制代码
 1 public class CountCharDemo {
 2 public static void main(String[] args) {  3 char key = '字';  4 String str = "统计一个字符在字符串中的所有位置";  5 int[] count=count(str,key);  6 System.out.println(Arrays.toString(count));//[4, 7]  7  }  8 public static int[] count(String str,char key){  9 int[] count={}; 10 for(int i=0;i<str.length();i++){ 11 char c=str.charAt(i); 12 if(c==key){ 13 //扩展数组 14 count=Arrays.copyOf(count, count.length+1); 15 //添加序号i 16 count[count.length-1]=i; 17  } 18  } 19 return count; 20  } 21 }
复制代码

 char[]、String、StringBuilder

  char[]:字符序列, 只有字符数据, 没有操作, 如果算法优秀, 性能最好。

  String: char[] + 方法(操作, API功能)
  StringBuilder: char[] + 方法(操作char[] 的内容)

  String:内部包含内容不可变的char[],表现为String对象不可变。String包含操作(API方法),是对char[]操作,但不改变原对象经常返回新的对象,很多String API提供了复杂的性能优化算法,如:静态字符串池。

  StringBuilder:内部也是一个char[],但是这个数组内容是可变的,并且自动维护扩容算法,因为数据内容可变,所以叫:可变字符串。StringBuilder API方法,是动态维护char[]内容,都可以改变char[]内容。

复制代码
 1 public abstract class AbstractStringBuilder {  2 /** The value is used for character storage.*/  3 char value[];  4 /** The count is the number of characters used.*/  5 int count;  6 /** Returns the length (character count).*/  7 public int length() {  8 return count;  9  } 10 11 public AbstractStringBuilder append(String str) { 12 if (str == null) 13 str = "null"; 14 int len = str.length(); 15 if (len == 0) 16 return this; 17 int newCount = count + len; 18 if (newCount > value.length) 19  expandCapacity(newCount); 20 str.getChars(0, len, value, count); 21 count = newCount; 22 return this; 23  } 24 25 /** 26  * 自动实现Java数组扩容 27 */ 28 void expandCapacity(int minimumCapacity) { 29 int newCapacity = (value.length + 1) * 2; 30 if (newCapacity < 0) { 31 newCapacity = Integer.MAX_VALUE; 32 } else if (minimumCapacity > newCapacity) { 33 newCapacity = minimumCapacity; 34  } 35 value = Arrays.copyOf(value, newCapacity); 36  } 37 }
复制代码

 字符串数组与String类的原理

复制代码
 1 /** 字符串数组与String类的原理 */
 2 public class CharArrayDemo {  3 public static void main(String[] args) {  4 /* Java 可以将char[]作为字符串处理 */  5 char[] ch1={'中','国','北','京'};  6 char[] ch2={'欢','迎','您'};  7 System.out.println(ch1);//中国北京  8 System.out.println(ch2);//欢迎您  9 /* char[]运算需要编程处理,如连接: */ 10 char[] ch3=Arrays.copyOf(ch1, ch1.length+ch2.length); 11 System.arraycopy(ch2, 0, ch3, ch1.length, ch2.length); 12 System.out.println(ch3);//中国北京欢迎您 13 /* String API提供了简洁的连接运算: */ 14 String str1="中国北京"; 15 String str2="欢迎您"; 16 String str3=str1.concat(str2); 17 System.out.println(str3);//中国北京欢迎您 18 /* 字符串转大写: */ 19 char[] ch4={'A','a','c','f'}; 20 char[] ch5=Arrays.copyOf(ch4, ch4.length); 21 for(int i=0;i<ch5.length;i++){ 22 char c=ch5[i]; 23 if(c>='a' && c<='z'){ 24 ch5[i]=(char)(c+('A'-'a')); 25  } 26  } 27 System.out.println(ch5);//AACF, 原数组ch4不变 28 String str4="Aacf"; 29 String str5=str4.toUpperCase();//原字符串str4保持不变 30 System.out.println(str5);//AACF 31  } 32 }
复制代码
作者: Candyメ奶糖

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
博文来源广泛,如原作者认为我侵犯知识产权,请尽快给我发邮件 359031282@qq.com联系,我将以第一时间删除相关内容。

目录
相关文章
|
1天前
|
Java 关系型数据库 MySQL
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
UWB (ULTRA WIDE BAND, UWB) 技术是一种无线载波通讯技术,它不采用正弦载波,而是利用纳秒级的非正弦波窄脉冲传输数据,因此其所占的频谱范围很宽。一套UWB精确定位系统,最高定位精度可达10cm,具有高精度,高动态,高容量,低功耗的应用。
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
|
1天前
|
设计模式 算法 Java
Java中的设计模式及其应用
【4月更文挑战第18天】本文介绍了Java设计模式的重要性及分类,包括创建型、结构型和行为型模式。创建型模式如单例、工厂方法用于对象创建;结构型模式如适配器、组合关注对象组合;行为型模式如策略、观察者关注对象交互。文中还举例说明了单例模式在配置管理器中的应用,工厂方法在图形编辑器中的使用,以及策略模式在电商折扣计算中的实践。设计模式能提升代码可读性、可维护性和可扩展性,是Java开发者的必备知识。
|
1天前
|
安全 Java API
函数式编程在Java中的应用
【4月更文挑战第18天】本文介绍了函数式编程的核心概念,包括不可变性、纯函数、高阶函数和函数组合,并展示了Java 8如何通过Lambda表达式、Stream API、Optional类和函数式接口支持函数式编程。通过实际应用案例,阐述了函数式编程在集合处理、并发编程和错误处理中的应用。结论指出,函数式编程能提升Java代码的质量和可维护性,随着Java语言的演进,函数式特性将更加丰富。
|
2天前
|
Java API 数据库
深入解析:使用JPA进行Java对象关系映射的实践与应用
【4月更文挑战第17天】Java Persistence API (JPA) 是Java EE中的ORM规范,简化数据库操作,让开发者以面向对象方式处理数据,提高效率和代码可读性。它定义了Java对象与数据库表的映射,通过@Entity等注解标记实体类,如User类映射到users表。JPA提供持久化上下文和EntityManager,管理对象生命周期,支持Criteria API和JPQL进行数据库查询。同时,JPA包含事务管理功能,保证数据一致性。使用JPA能降低开发复杂性,但需根据项目需求灵活应用,结合框架如Spring Data JPA,进一步提升开发便捷性。
|
3天前
|
数据采集 算法 数据可视化
R语言聚类算法的应用实例
R语言聚类算法的应用实例
80 18
R语言聚类算法的应用实例
|
3天前
|
算法 数据可视化 数据挖掘
R语言社区主题检测算法应用案例
R语言社区主题检测算法应用案例
|
7天前
|
Java
探秘jstack:解决Java应用线程问题的利器
探秘jstack:解决Java应用线程问题的利器
15 1
探秘jstack:解决Java应用线程问题的利器
|
7天前
|
算法
算法系列--两个数组的dp问题(2)(下)
算法系列--两个数组的dp问题(2)(下)
13 0
|
7天前
|
存储 算法
算法系列--动态规划--⼦数组、⼦串系列(数组中连续的⼀段)(1)(下)
算法系列--动态规划--⼦数组、⼦串系列(数组中连续的⼀段)(1)
13 0
|
7天前
|
算法
算法系列--动态规划--⼦数组、⼦串系列(数组中连续的⼀段)(1)(上)
算法系列--动态规划--⼦数组、⼦串系列(数组中连续的⼀段)(1)
16 0