会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132358个问题
JAVA 全系列/第二阶段:JAVA 基础深化和提高/手写服务器项目(旧) 3917楼

问题点:同样是打印集合,为什么

System.out.println(list);
打印的是地址
System.out.println(list2);
打印的是集合
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**(1)toarray()
 *     public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }
 * */

public class Test {
	public static void main(String[] args){
		/**集合转成数组*/
		ArrayList<String> a1 = new ArrayList<String>();
		a1.add("hello");
		a1.add("hello");
		a1.add("hello");
		Object[] obj = a1.toArray();
		for(Object object: obj){
			System.out.println(object);
		
		}
		System.out.println("_____________");
		String []strArray = new String[1];//创建数组对象
		strArray = a1.toArray(strArray);   //用toArray()方法把集合转成数组
		for(String str: strArray){
			System.out.println(str);
		}
		/**数组转成集合
		 * public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }
		 * */
		int [] array = {11,22,33};
		List list = Arrays.asList(array);//相当创建新的ArrayList对象
		System.out.println(list);
		
		System.out.println("------------");
		Integer[] array2 = new Integer []{11,22,33};
		List <Integer> list2 = Arrays.asList(array2);
		System.out.println(list2);
	}

}

打印:

image.png

JAVA 全系列/第二阶段:JAVA 基础深化和提高/容器(旧) 3919楼

说句玩笑话,关于ThreadLocal 分析的视频是认真做的吗?

 

  1. 关于set方法和get方法的顺序问题,视频先介绍的set方法

    set.png

    视屏并未说明为何3个ThreadLocalMap中的Number为何不是同一个对象?因为我们要保证的ThreadLocalMap 键值对对象中的value值为不同的?实际上传入的value对象才是关键吧。

    此set方法只是展示了:将value设置到自己线程的ThreadLocalMap键值对中,其中key为线程对象本身,值为value对象;但是并不能判断对象(图示中的number为不同的对象)

     

2.实际上set方法之所以设置的value为不同的对象,是因为get方法,

QQ截图20190109180939.png

视频中分析的get方法通过线程对象得到value 而get方法源码为:

public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

正是由于第一次执行get方法时,ThreadLocalMap map = getMap(t);中map为null

所以执行 return setInitialValue();其中setInitialValue()方法源码为:

private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

是因为第一次执行setInitialValue()方法时,返回的是执行 ,T value = initialValue();中value的值

而 initialValue()方法是我们自己实现的;

也就是说,每个ThreadLocalMap键值对的值的初始值(对象),都是通过initialValue()方法新创建不同对象。因为是不同的对象,但是状态相同,所以才有每个副本的值相同吧.

所以视频的源码分析是故意没讲完全?

    

JAVA 全系列/第二阶段:JAVA 基础深化和提高/多线程和并发编程(旧) 3921楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/XML 技术(旧) 3922楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/XML 技术(旧) 3923楼

在使用HashSet容器时为什么Person类必须重写hashCode()方法及equals()方法,不重写一样可以储存啊

代码:

package cn.sxt.set;

public class Person {
	private String name;
	private int age;
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
/*	//Person 类必须重写hashCode()方法和equals()方法
	//Hash表原理
	*//**
	 * (1)调用hashCode()方法计算Hash码值
	 * (2)根据y=k(x)这样的函数计算储存位置
	 * (3)如果该位置上没有元素,则元素储存
	 * (4)如果有元素,则调用equals方法比较内容,若相同,则不储存,若不同,则储存
	 * *//*
	public int hashCode(){
		System.out.println("person.hashCode()");
		final int prime = 31;
		int result = 1;
		result = prime*result +age;
		result = prime*result + ((name==null)?0:name.hashCode());
		return result;
		
	}
	public boolean equals(Object obj){
		
	    System.out.println("Person.equsls()");
	    if(this == obj)
	    	return true;
	    if(obj==null)
	    	return false;
	    if(getClass() !=obj.getClass())
	    	return false;
	    Person other = (Person) obj;
	    if(age !=other.age)
	    	return false;
	    if(name == null){
	    	if(other.name!=null)
	    		return false;
	    }else if(!name.equals(other.name))
	    	return false;
	    return true;
	    	
	    
	    
	   }*/
	
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
	

}
package cn.sxt.set;

import java.util.HashSet;

public class TestPersonHashSet {
	public static void main(String[]args){
		
		HashSet hs = new HashSet();
		Person p = new Person("may",18);
		Person p1 = new Person("jak",20);
		Person p2 = new Person("may",22);
		Person p3 = new Person("lili",20);
		hs.add(p);
		hs.add(p2);
		hs.add(p1);
		hs.add(p3);
		System.out.println(hs);
		
	}

}

打印:

image.png

JAVA 全系列/第二阶段:JAVA 基础深化和提高/容器(旧) 3924楼

package com.bjsxt.file;
import java.io.File;
import java.io.IOException;

public class TestFile {
    //使用File类操作文件
    public static void main(String[] args) throws IOException {
        //创建File类的对象
        //File f1 = new File("\\Users\\wanglx\\Desktop\\测试图片\\140F1132T93X.txt");//绝对路径
        File f2 = new File ( "/Users/wanglx/Desktop/测试图片/140F1132T93X.txt" );
        File f3 = new File ( "140F1132T93X.txt" );//相对路径
        File f4 = new File ("/Users/wanglx/Desktop/测试图片");//目录
        File f5 = new File ( f4,"140F1132T93X.txt" );//目录下的某个文件
        File f6 = new File ( "Desktop"+File.separator+"140F1132T93X.txt" );//获取系统相关的路径分隔符separator
        /**File操作文件相关的方法*/
        System.out.println (f2.createNewFile ());
       // System.out.println (f2.delete ());//直接从磁盘上删除
        System.out.println (f2.exists ());//不存在返回false
        System.out.println ("绝对路径:"+f3.getAbsolutePath ());
        System.out.println ("相对路径:"+f3.getPath ());
        System.out.println ("获取文件名:"+f3.getName ());
        System.out.println (f3.toString ());//相对路径
        System.out.println ("f3是否是文件:"+f3.isFile ());
        System.out.println ("是否是文件:"+f4.isFile ());

    }
}


 System.out.println ("f3是否是文件:"+f3.isFile ());

返回结果:false

为什么呢

JAVA 全系列/第二阶段:JAVA 基础深化和提高/常用类 3926楼

image.png

package com.bjsxt.copy;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestCopy {
	public static void main(String[] args) {
		File srcDir=new File("D:\\信息");
		File targetDir=new File("D:\\信息");
		copyDir(srcDir, targetDir);
	}
	public static void copyDir(File srcDir,File targetDir){
		if(!targetDir.exists()){
			targetDir.mkdir();
		}
		File []files=srcDir.listFiles();
		for(File file : files){
			if(file.isFile()){
				copyFile(new File(srcDir+"\\"+file.getName()),new File(targetDir+"\\"+file.getName()) );
				
			}
			else{
				copyFile(new File(srcDir+"\\"+file.getName()),new File(targetDir+"\\"+file.getName()) );
				
			}
		}
	}
	public static void copyFile(File src,File target){
		
		//提高读取速率。从数据源
		BufferedInputStream bis=null;
		//提高写入效率,写到目的地
		BufferedOutputStream bos=null;
		try {
			bis = new BufferedInputStream(new FileInputStream(src));
			bos = new BufferedOutputStream(new FileOutputStream(target));
			//边读边写
			byte [] buf=new byte[1024];
			int len=0;
			while((len=bis.read())!=-1){
				bos.write(buf, 0, len);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			//关闭
			if(bis!=null){
				try {
					bis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(bos!=null){
				try {
					bos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
	
	} 
}

为什么会出现文件无法访问啊!什么原因引起的,我这个文件夹里只放了一个文档文件!

JAVA 全系列/第二阶段:JAVA 基础深化和提高/IO 流技术(旧) 3927楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637