java中使用ArrayList如何修改里面的内容.
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java中使用ArrayList如何修改里面的内容.相关的知识,希望对你有一定的参考价值。
程序请看:http://zhidao.baidu.com/question/50252674.html
如果我要对Score进行修改应该怎么做呢?
////////////////that's mine
import java.util.*;
public class StudentSorter
public static void main(String [] as)
Student a = new Student("a", 80);
Student b = new Student("b", 90);
Student c = new Student("c", 70);
List<Student> list = new ArrayList<Student>();
list.add(a);
list.add(b);
list.add(c);
System.out.println("未修改前:");
for(Student s: list)
System.out.println(s);
a.setMark(100);
list.set(0, a);
System.out.println("已修改后:");
for(Student s: list)
System.out.println(s);
class Student implements Comparable
private String name;
private int mark;
public Student()
public Student(String n, int m)
name = n;
mark = m;
public void setMark(int m)
mark = m;
public int getMark()
return mark;
public int compareTo(Object o)
if(o instanceof Student)
Student s = (Student)o;
return s.getMark() - this.getMark();
else
return -1;
public String toString()
return name + ": " + mark;
做法就是上面的。
扩展资料:
java中ArrayList用法详解
基本的ArrayList,长于随机访问元素,但是在List中间插入和移除元素时较慢,并且ArrayList的操作不是线程安全的。
一般在单线程中才使用ArrayList,而在多线程中一般使用Vector或者CopyOnWriteArrayList。
1、使用ArrayList 简单的例子:
ArrayList<Integer> a=new ArrayList<Integer>();
for(int i=0; i<n; i++)
a.add(sc.nextInt()); //为数组增加int型数
a.remove(0);//删除第一个元素;
m=2;
a.add(m); //在数组末尾添加
a.add(4,2);// 在指定位置添加元素,在第5个位置添加2
a.remove(2); // 删除指定位置上的元素
a.remove((Object)3); // 删除指定元素
a.clear(); // 清空ArrayList
System.out.println("ArrayList contains 5 is: " + a.contains(5));// 判断arrayList是否包含5
System.out.println("ArrayList is empty: " + arrayList.isEmpty()); // 判断ArrayList是否为空
2、toArray用法
有时候,当我们调用ArrayList中的 toArray(),可能遇到过抛出java.lang.ClassCastException异常的情况,
这是由于toArray() 返回的是 Object[] 数组,将 Object[] 转换为其它类型(如,将Object[]转换为的Integer[])则会抛出java.lang.ClassCastException异常,因为Java不支持向下转型。
所以一般更常用的是使用另外一种方法进行使用:
<T> T[] toArray(T[] a)
调用toArray(T[] a)返回T[]可通以下方式进行实现:
// toArray用法
// 第一种方式(最常用)
Integer[] integer = arrayList.toArray(new Integer[0]);
// 第二种方式(容易理解)
Integer[] integer1 = new Integer[arrayList.size()];
arrayList.toArray(integer1);
// 抛出异常,java不支持向下转型
//Integer[] integer2 = new Integer[arrayList.size()];
//integer2 = arrayList.toArray();
ArrayList<Integer> a = new ArrayList<Integer>();
实例:
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListDemo
public static void main(String[] srgs)
ArrayList<Integer> arrayList = new ArrayList<Integer>();
System.out.printf("Before add:arrayList.size() = %d\\n",arrayList.size());
arrayList.add(1);
arrayList.add(3);
arrayList.add(5);
arrayList.add(7);
arrayList.add(9);
System.out.printf("After add:arrayList.size() = %d\\n",arrayList.size());
System.out.println("Printing elements of arrayList");
// 三种遍历方式打印元素
// 第一种:通过迭代器遍历
System.out.print("通过迭代器遍历:");
Iterator<Integer> it = arrayList.iterator();
while(it.hasNext())
System.out.print(it.next() + " ");
System.out.println();
// 第二种:通过索引值遍历
System.out.print("通过索引值遍历:");
for(int i = 0; i < arrayList.size(); i++)
System.out.print(arrayList.get(i) + " ");
System.out.println();
// 第三种:for循环遍历
System.out.print("for循环遍历:");
for(Integer number : arrayList)
System.out.print(number + " ");
// toArray用法
// 第一种方式(最常用)
Integer[] integer = arrayList.toArray(new Integer[0]);
// 第二种方式(容易理解)
Integer[] integer1 = new Integer[arrayList.size()];
arrayList.toArray(integer1);
// 抛出异常,java不支持向下转型
//Integer[] integer2 = new Integer[arrayList.size()];
//integer2 = arrayList.toArray();
System.out.println();
// 在指定位置添加元素
arrayList.add(2,2);
// 删除指定位置上的元素
arrayList.remove(2);
// 删除指定元素
arrayList.remove((Object)3);
// 判断arrayList是否包含5
System.out.println("ArrayList contains 5 is: " + arrayList.contains(5));
// 清空ArrayList
arrayList.clear();
// 判断ArrayList是否为空
System.out.println("ArrayList is empty: " + arrayList.isEmpty());
/**
Before add:arrayList.size() = 0
After add:arrayList.size() = 5
Printing elements of arrayList
通过迭代器遍历:1 3 5 7 9
通过索引值遍历:1 3 5 7 9
for循环遍历:1 3 5 7 9
ArrayList contains 5 is: true
ArrayList is empty: true
*/
参考技术Ajava中使用arraylist修改里面的内容,可以使用set方法,拿到下标修改内容,如下代码:
package com.qiu.lin.he;import java.util.ArrayList;
import java.util.List;
public class Ceshi
public static void main(String[] args)
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
System.out.println("未修改前:");
for (String s : list)
System.out.println(s);
list.set(0, "修改之后的元素");//修改对应的元素
System.out.println("已修改后:");
for (String s : list)
System.out.println(s);
运行结果如下:
import java.util.List;
public class test1
public static void main(String[] args)
List<Integer> list2 = new ArrayList<Integer>();
list2.add(1);
list2.add(2);
list2.add(3);
list2.add(4);
list2.set(2, 7);
for(int i = 0 ; i < list2.size(); i++)
System.out.println(list2.get(i));
这样就行了
他的API是
set(int index, E element)
用指定元素替换列表中指定位置的元素(可选操作)。 参考技术C ////////////////that's mine
import java.util.*;
public class StudentSorter
public static void main(String [] as)
Student a = new Student("a", 80);
Student b = new Student("b", 90);
Student c = new Student("c", 70);
List<Student> list = new ArrayList<Student>();
list.add(a);
list.add(b);
list.add(c);
System.out.println("未修改前:");
for(Student s: list)
System.out.println(s);
a.setMark(100);
list.set(0, a);
System.out.println("已修改后:");
for(Student s: list)
System.out.println(s);
class Student implements Comparable
private String name;
private int mark;
public Student()
public Student(String n, int m)
name = n;
mark = m;
public void setMark(int m)
mark = m;
public int getMark()
return mark;
public int compareTo(Object o)
if(o instanceof Student)
Student s = (Student)o;
return s.getMark() - this.getMark();
else
return -1;
public String toString()
return name + ": " + mark;
本回答被提问者采纳 参考技术D 不是结了么?
java在filter中修改一个http请求出入参内容
response保存了请求的返回信息,里面有个outputstream,你要返回给页面的流,都在这个地方保存.
之前遇到一个问题,想把outputstream修改一下.因为这是个输出流,想要改这个里面的东西不是这么简单的.
sun为我们提供了这么一个工具HttpServletResponseWrapper抽象类,利用这个类的子类把servletresponse包装一下,在过滤器中使用,就可以去除response的文件流,对其作出修改.给出一个实现:
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;
/**
* ResponseWrapper
*
* @author wuweifeng
* @version 1.0
* @date 2021-08-16
*/
public class ResponseWrapper extends HttpServletResponseWrapper
/**
* ByteArrayOutputStream
*/
private ByteArrayOutputStream buffer;
/**
* ServletOutputStream
*/
private ServletOutputStream out;
/**
* writer
*/
private PrintWriter writer;
/**
* ResponseWrapper
*/
public ResponseWrapper(HttpServletResponse resp) throws IOException
super(resp);
buffer = new ByteArrayOutputStream();//真正存储数据的流
out = new WrapperOutputStream(buffer);
writer = new PrintWriter(new OutputStreamWriter(buffer, this.getCharacterEncoding()));
//重载父类获取outputstream的方法
@Override
public ServletOutputStream getOutputStream() throws IOException
return out;
//重载父类获取writer的方法
@Override
public PrintWriter getWriter() throws UnsupportedEncodingException
return writer;
//重载父类获取flushBuffer的方法
@Override
public void flushBuffer() throws IOException
if (out != null)
out.flush();
if (writer != null)
writer.flush();
@Override
public void reset()
buffer.reset();
/**
* 获取response的字符串
*/
public String getContent() throws IOException
flushBuffer();//将out、writer中的数据强制输出到WapperedResponse的buffer里面,否则取不到数据
return new String(buffer.toByteArray());
//内部类,对ServletOutputStream进行包装
private class WrapperOutputStream extends ServletOutputStream
/**
* ByteArrayOutputStream
*/
private ByteArrayOutputStream bos;
/**
* WrapperOutputStream
*/
WrapperOutputStream(ByteArrayOutputStream stream)
bos = stream;
@Override
public void write(int b)
bos.write(b);
@Override
public boolean isReady()
return false;
@Override
public void setWriteListener(WriteListener writeListener)
然后在你的过滤器中这么使用:
public class UserFilter implements Filter
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
HttpServletResponse resp = (HttpServletResponse) servletResponse;
ResponseWrapper mResp = new ResponseWrapper(resp);// 包装响应对象 resp 并缓存响应数据
filterChain.doFilter(servletRequest, mResp);
String content = mResp.getContent();//response流的内容
System.out.println(content);
//此处可以对content做处理,然后再把content写回到输出流中
servletResponse.setContentLength(-1);
PrintWriter out = servletResponse.getWriter();
out.write(content);
out.flush();
out.close();
关于入参request的,如果只是key-value型的,对应客户端是form那种传过来的,在filter里直接获取没事。但如果是application/json型的,如果这个输入流被提前读取了,则后续真正的controller就取不到了,也需要做个包装类。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import static com.alibaba.fastjson.util.IOUtils.UTF8;
public class RequestWrapper extends HttpServletRequestWrapper
/**
* log
*/
private static final Logger log = LoggerFactory.getLogger(RequestWrapper.class);
/**
* application/json型的入参
*/
private final String body;
/**
* key-value型所有的入参
*/
private Map<String, String[]> params = new HashMap<>();
public RequestWrapper(HttpServletRequest request)
super(request);
this.params.putAll(request.getParameterMap());
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
InputStream inputStream = null;
try
inputStream = request.getInputStream();
if (inputStream != null)
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, UTF8));
char[] charBuffer = new char[512];
int bytesRead;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0)
stringBuilder.append(charBuffer, 0, bytesRead);
catch (IOException ex)
log.error("requestBody read error ignore,message:" + ex.getMessage());
finally
if (inputStream != null)
try
inputStream.close();
catch (IOException e)
log.error("requestBody inputStream close error,ignore");
if (bufferedReader != null)
try
bufferedReader.close();
catch (IOException e)
log.error("requestBody bufferedReader close error,ignore");
body = stringBuilder.toString();
@Override
public ServletInputStream getInputStream() throws IOException
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes(UTF8));
ServletInputStream servletInputStream = new ServletInputStream()
@Override
public boolean isFinished()
return false;
@Override
public boolean isReady()
return false;
@Override
public void setReadListener(ReadListener readListener)
@Override
public int read() throws IOException
return byteArrayInputStream.read();
;
return servletInputStream;
@Override
public BufferedReader getReader() throws IOException
return new BufferedReader(new InputStreamReader(this.getInputStream(), UTF8));
public String getBody()
return this.body;
@Override
public String getParameter(String name)
String[] values = params.get(name);
if (values == null || values.length == 0)
return null;
return values[0];
@Override
public String[] getParameterValues(String name)
return params.get(name);
@Override
public Enumeration<String> getParameterNames()
return Collections.enumeration(params.keySet());
以上是关于java中使用ArrayList如何修改里面的内容.的主要内容,如果未能解决你的问题,请参考以下文章
如何从 ArrayList (Java) 中存储另一个数组的 ArrayList 获取数据?