Java学习中的不解

一直以来,都是用C,C++,C#开发程序,从事的也是编译器相关方面的研究与开发,最近在测试方面有些比较好的想法,想从实验的角度验证想法是否可行。但C系列里面没有相关的benchmark,只有Java有,所以转而学习Java。Java中的语法基本与C++一致,上手很容易,但是有些地方依然不太顺手,故而本文记录本人在开发Java程序过程中遇到的问题,作为笔记。

1 参数传递问题。在Java中,参数传递没有C++中默认的传值以及传引用等相关标记,在Java中,内置类型对象参数采用传值方式,而类对象参数这采用引用传递。注意:Java中的String是类,而非内置对象;

2 集合使用问题。在C++中,STL非常好用;在Java中,也有List<>, Map<>, Set<>,Queue<>等容器,在使用Map时必须注意,其中的关键字必须是类,而不允许是内置类型,容器中的类型对象必须继承于Object。

3 在Java中const是保留字,具体用法不解。如果需要定义常量,可以使用final关键字

4 List<String>的contains用法,由于比较时用的事 (o==null ? e==null : o.equals(e)),即不是比较地址,而是比较两个对象中的内容

5 泛型比C++中更灵活,一样的分为类泛型和函数泛型(摘自官方Java tutorial)。函数泛型如:

public final class Algorithm {
    public static <T>
        int findFirst(List<T> list, int begin, int end, UnaryPredicate<T> p) {

        for (; begin < end; ++begin)
            if (p.test(list.get(begin)))
                return begin;
        return -1;
    }
}

类泛型如:

View Code
 1 public class Pair<K, V> {
 2 
 3     public Pair(K key, V value) {
 4         this.key = key;
 5         this.value = value;
 6     }
 7 
 8     public K getKey(); { return key; }
 9     public V getValue(); { return value; }
10 
11     public void setKey(K key)     { this.key = key; }
12     public void setValue(V value) { this.value = value; }
13 
14     private K key;
15     private V value;
16 }

错误的例子1,原因:不能创建静态类型的泛型参数

View Code
 1 public class Singleton<T> {
 2 
 3     public static T getInstance() {
 4         if (instance == null)
 5             instance = new Singleton<T>();
 6 
 7         return instance;
 8     }
 9 
10     private static T instance = null;
11 }

错误的例子2,原因:继承关系错误

View Code
1 class Shape { /* ... */ }
2 class Circle extends Shape { /* ... */ }
3 class Rectangle extends Shape { /* ... */ }
4 
5 class Node<T> { /* ... */ }
6 
7 Node<Circle> nc = new Node<>();
8 Node<Shape>  ns = nc;  // error

 

posted @ 2012-12-10 13:42  iosJohnson  阅读(266)  评论(0编辑  收藏  举报