`
iloveflower
  • 浏览: 76764 次
社区版块
存档分类
最新评论
  • iloveflower: 呵呵。好好学习。。。。。。。。。。。。
    java 读书
  • Eric.Yan: 看了一点,不过是电子版的……你这一说到提醒我了,还要继续学习哈 ...
    java 读书

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);

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics