我的随笔5

  1. 如何高效率的遍历 Map

public static void main(String[] args) {
Map<String, String> maps = new HashMap<String, String>(); maps.put(“111”, “张三”);

Set keySet = maps.keySet(); //取出所有键的集合

java.util.Iterator iterator = keySet.iterator(); //获取 Iteratro

while(iterator.hasNext()){ //判断迭代器是否存在数据

String key = (String)iterator.next(); //遍历取出所有键

String value = maps.get(key); //根据键获取值

System.out.println(“键:”+key+",值:"+value);

}

}

  1. 二分查找法

public static int binarySearch(int[] arr, int target) {
int len = arr.length - 1; //终止下标

int start = 0; //起始下标

while (start <= len) { //二分
int middle = (start + len) / 2; //当中间的值等于目标值时,返回下标if (target == arr[middle]) {
return middle;
}
//当中间值大于目标值时,说明目标值在前半部分,
// 起始值不变,终止值为中间值-1 if (arr[middle] > target) {
len = middle - 1;
}
//当中间值大于目标值时,说明目标值在后半部分,
// 终止值不变,起始值为中间值+1 if (arr[middle] < target) {
start = middle + 1;
}
}
return -1;

}

  1. 冒泡排序

int[] sa = new int[]{49, 38, 98, 54, 76, 13, 27, 1};
for (int i = 0; i < sa.length - 1; i++) {
for (int j = 0; j < sa.length - 1 - i; j++) {
//当前一位数大于后面的数时,将位置替换if (sa[j] > sa[j + 1]) {
int b = sa[j]; sa[j] = sa[j + 1]; sa[j + 1] = b;
}
}
System.out.print((i + 1) + “次循环:”); for (int t : sa) {

System.out.print(t + " ");

}
System.out.println();

}

  1. 递归

public static void main(String[] args) {

//3628800 System.out.println(mulitiply(10));

}

//1098765432*1

static int mulitiply(int n){

if(n0||n1){

return n;

}else {
return

n*mulitiply(n-1);

}

}

  1. 写一个单例模式

单例模式:确保一个类只有一个实例,并提供一个全局访问点,一般分类两大类: 饿汉模
式、懒汉模式
/**

  • 饿汉模式, 线程安全, 但默认就创建实例, 占用空间*/
    public class Singleton1 {
    private static final Singleton1 instance = new Singleton1();

private Singleton1() { }

public static Singleton1 getIntance() {
return instance;
}
}
/**

  • 懒汉模式, 线程不安全*/
    public class Singleton2 {
    private static Singleton2 instance = null;

private Singleton2() { }

public static Singleton2 getInstance() {
if (instance == null) {
instance = new Singleton2();
}
return instance;
}

}

//使用
public class SingletonPatternDemo {
public static void main(String[] args) {

//不合法的构造函数
//编译时错误:构造函数 Singleton1() 是不可见的//Singleton1 object = new Singleton1();

//获取唯一可用的对象
Singleton1 object = Singleton1.getIntance(); }
}

  1. 两数互换,不使用第三变量

int a =20;

int b = 30; System.out.println("初始

a 值为:"+a+",初始

b 值为:"+b);

b = a*b; //b=600

a = b/a; //600/20 =30

b = b/a; //600/30 =20

System.out.println(“互换后 a 值为:”+a+",b 值为:"+b);

  1. 文件操作

参考本地文件: E:\使用 java 实现面向对象编程\第八章、File IO\src\自由练习\FileClassCaoZuo - 副本.txt

  1. 统计字符串中出现的字母、空格、数字和其他字符出

现的次数

String str = “3jhf8 87d .d#@发 4 er”;

int countNum, countWork, countblank, countOther =0;

char[] ch = str.toCharArray();

for (char c : ch) {

if(c>=‘0’&&c<=‘9’){
countNum++;

}else if(c>=‘A’&&c<=‘Z’||c>=‘a’&&c<=‘z’){

countWork++;

}else if(c==’ '){

countblank++; }else{
countOther++;
}

}

  1. 数组去重并排序

int[] nums = {43,13,78,35,23,43,68,35,13};

//使用HashSet去重

HashSet hashSet = new HashSet<>();

for (int i = 0;i<nums.length;i++){

hashSet.add(nums[i]);

}

//利用TreeSet排序
Set set = new

TreeSet<>(hashSet);

Integer[] ints = set.toArray(new Integer[]{});

//结果存放,设置数组长度

int[] result = new int[ints.length];

//添加进数组

for (int i=0;i<ints.length;i++){

result[i]=ints[i].intValue();

}
//输出

for (int i : result) {

System.out.println(i);

}

  1. 反射的使用

//获取这个类的对象
Class rc = Class.forName(“com.kcbg.reflect.Robot”);

//输出这个类的name 全类名:com.kcbg.reflect.Robot

System.out.println("Class name is "+rc.getName());

//创建这个类的实例
Robot robot = (Robot) rc.newInstance();
//getDeclaredMethod获取声明的方法,不管是否私有,不过无法获取到基类及其接口的方法
//String.class表示该方法要接收一个String的参数
Method getHello = rc.getDeclaredMethod(“throwHello”, String.class); //设置为true,默认为true,因为是获取私有的方法,不设置会报错getHello.setAccessible(true);

Object str = getHello.invoke(robot,“Bob”);

System.out.println("getHello result is "+ str); HelloBob

//只能获取public方法和基层所实现的接口的方法
Method sayHi = rc.getMethod(“sayHi”, String.class);

sayHi.invoke(robot,“Welcome”); //Welcomenull

//获取私有属性
Field name = rc.getDeclaredField(“name”); name.setAccessible(true); name.set(robot,“Alice”);

sayHi.invoke(robot,“Welcome”); //WelcomeAlice

  1. 文件上传

太多了,不写又不好,你的简历上面有关于文件上传,,自己看看以前的代码就好,不贴上来了

就放几个关键字:<form … . enctype=“multipart/form-data”>

void Useraddsave(MultipartFile attach) //参数attach.getOriginalFilename(); //原文件名FilenameUtils.getExtension(//原文件名); //原文件后缀attach.getSize(); //原文件大小
//将MultipartFile对象attach中文件流的数据输出至目标路径中
attach.transferTo(newFile);

  1. 字符串反转

使用 StringBuilder 或者 stringBuffer 的 reverse() 方法。代码示例:
StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(“abcdefg”); System.out.println(stringBuffer.reverse()); // gfedcba

  1. Spring 如何实现切面(AOP)

@Aspect //定义切面

@Component //因为是 springBoot 项目,需将其加入配置类

public class HelloAspect {

//定义切入点(切入位置) ….(…)代表任意参数任意名字的方法都执行切入

@Pointcut(“execution(public * com.bdqn.controller….(…))”)

public void webLog(){ } //给该切入点起名

@Before(“webLog()”) //Before:前置增强,执行切入点的方法时执行这个方法

public void deBefore(JoinPoint jp){

logger.info(“前置增强”);

}
//后面还有 @AfterReturning()后置增强@AfterThrowing() 异常抛出增强@After()最终增强
@Around()环绕增强、

  1. 实现Callable 接口通过FutureTask 包装器来创建线程

//创建Callable接口的实现类,并实现Call方法

public class Tickets implements Callable {

@Override

public Object call() throws Exception {

System.out.println(Thread.currentThread().getName()+"–>我是通过实

现 Callable 接口通过 FutureTask 包装器来实现的线程");

return null; //带返回值

}

}

public class ThreadDemo01 {

public static void main(String[] args) {

//创建Callable实现类的实现Callable oneCallable = new

Tickets();

//使用FutureTask类包装Callable对象,该对象封装了Callable对象Call
方法的返回值

FutureTask oneTask = new FutureTask(oneCallable);

//使用FutureTask对象作为Thread对象的target创建并启动线程

Thread t = new Thread(oneTask);

System.out.println(Thread.currentThread().getName()); t.start();

}

}

  1. 强、软、弱、虚引用代码示例

//强引用

String str = new String(“abc”);

//去掉强引用str = null; //再次强引用

str = new String(“edf”);

//软引用softReference SoftReference softReference = new

SoftReference<>(str);

//弱引用weakReference WeakReference weakReference = new

WeakReference<>(str);

//引用队列
ReferenceQueue referenceQueue = new

ReferenceQueue<>();

//定义虚引用
PhantomReference phantomReference = new PhantomReference<>(str,referenceQueue);
//不管在什么情况下,虚引用始终返回null System.out.println(phantomReference.get());
//那它是空,作用是?我们将它放入了引用队列,,可以从引用队列取出虚引用,执行它的析构动作
str = null; //清空强引用System.gc(); //启动垃圾回收//把虚引用从引用队列中取出
Object obj = referenceQueue.poll();

if

(obj != null){
Field rereferenVal = null;
try {
//通过反射,得到待回收的值
rereferenVal = Reference.class.getDeclaredField(“refereent”);

rereferenVal.setAccessible(true);

System.out.println(“Before GC Clear:”+rereferenVal.get(obj).toString());

//可以在这里执行其他回收前的动作

} catch (NoSuchFieldException | IllegalAccessException e) {

e.printStackTrace();

}

}
//通过虚引用,我们可以在对象被回收后通过引用队列调用该对象的析构操作

  1. NIO 使用

int bufferSize = 1024; //定义缓冲区长度

FileChannel src = null,dest = null;

try

{
//定义了两个FileChannel对象,用来指向待读写的文件
src = new FileInputStream(“E:\demo\students1.txt”).getChannel(); dest = new FileOutputStream(“E:\demo\students3.txt”).getChannel();

//通过allocate方法给ByteBuffer分配空间//除了ByteBuffer缓冲器,还有

CharBuffer\DoubleBuffer\FloatBuffer\Int…Long等缓冲器,方便读写各种类型数据
//还有一个是MappedByteBuffer内存映射文件缓冲器,可以操作那些因为太大而不方便放入内存的文件
ByteBuffer buffer = ByteBuffer.allocate(bufferSize);

//通过while循环从src里逐行读取

while ((src.read(buffer) != -1)) {

buffer.flip(); //切换读写模式

dest.write(buffer); //向dest写入内容

buffer.clear(); //清空缓存,以便下次读

}
} catch

(FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try

{ src.close(); dest.close();

}catch (IOException e){

e.printStackTrace();

}

  1. 在数组元素中找出最大数和第二大数

int[] counts = {11,98,4,75,32}; //给出的数组

int max=counts[0]; //最大数

int second_max=counts[0]; //第二大数

//遍历数组

for (int count : counts) {

//当当前元素大于目前最大数时,将当前最大数max赋予第二大数second_max,
将当前元素值count赋予最大数max
if(count<max){ second_max=max; max=count;

}else{ //当当前元素小于目前最大数时(那这就肯定不是最大数了)

if(count>second_max){ //则判断是否大于第二大数,大于则将当前数

赋予第二大数
second_max=count;
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值