11

java有没有类似指针的集合

 3 years ago
source link: https://www.oschina.net/question/3447476_2322005
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

java有没有类似指针的集合

Jessica丶 发布于 前天 18:02
阅读 174

我有一个集合{“a”,“b”,"c"},我想在b之前插入d,最后结果是{“a”,"d",“b”,"c"},java该用什么集合处理

tcxu

前天 21:35

在java里面没有指针的定义。java将创建的对象存放在堆里,当用操作符 new 创建一个对象的时候,就在堆中开辟了一个存储该对象的空间,返回给引用的就是在堆中存储该对象的地址。所以说,java中所谓的对象引用,就是指针。

创建下列 泛型集合:java.util.ArrayList 的一个对象/实体, 就得到了这个实体的“指针”, 即 它的引用。通过这个引用,调用其成员方法,就能达到在集合的特定位置插入给定元素的目的。

import java.util.*;
public class Test{

public static void main(String[] args) {  
    String a []={"a","b","c"};
    String s ="abc";
    List<String> list = new ArrayList<String>();
    for (int i=0;i<a.length;i++)
    list.add(a[i]);
    list.add(list.indexOf("b"),"d");
   System.out.println(list);
    }      
}  

up-f99a051012feac6668972dfead92d7a8866.png

如果集合的每个元素都是单个字符,那就可以当成字符串来处理。

public class Test{

public static void main(String[] args) {  
    String s ="abc"; 
   	String result = s.substring(0,s.indexOf('b')) + 'd'+s.substring(s.indexOf('b'));
   	System.out.println(result);  
    }      
}  

up-ca08035ae64b6ec789d07ced4bfa1a7fcf2.png


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK