How to sort an array,mid of linkedlist, reverse int

A common mistake for a beginner to Java is to try and write some more or less complex method for sorting an array when in fact it can be done with just one line of code.
The Arrays class has a static method called sort which exists in many overloaded versions so you can pass in an array of any primitive type, or pass in an array of Strings or other Objects.
Since it is the reference of the array that is passed to the sort method nothing needs to be returned from it, the array is altered through the reference.
The example below shows two nearly identical methods, one that sorts an int array, and one that sorts an array of Strings.
import java.util.Arrays;

/**
*
* @author javadb.com
*/
public class Main {

/**
* Example method for sorting an int array
*/
public void sortIntArray() {

int[] arrayToSort = new int[] {48, 5, 89, 80, 81, 23, 45, 16, 2};

Arrays.sort(arrayToSort);

for (int i = 0; i < arrayToSort.length; i++)
System.out.println(arrayToSort[i]);
}

/**
* Example method for sorting a String array
*/
public void sortStringArray() {

String[] arrayToSort = new String[] {"Oscar", "Charlie", "Ryan", "Adam", "David"};

Arrays.sort(arrayToSort);

for (int i = 0; i < arrayToSort.length; i++)
System.out.println(arrayToSort[i]);
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Main main = new Main();
main.sortIntArray();
main.sortStringArray();
}
}
how to reverse a integer
既然都转成了String为什么不用StringBuffer呢
String str = StringBuffer.reverse(String.valueOf(integer)).toString();
return Integer.parseInt(s);
最多多三行解决问题。

public int reverse(int a){
return Integer.parseInt(new StringBuilder(String.valueOf(a)).reverse().toString());
}

LinkedList list = ...
int size = list.size();
int middle = (size / 2) + (size % 2 == 0 ? 0 : 1) - 1; //index of middle item
Object o = list.get(middle); //or ListIterator it = list.listIterator(middle);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值