Parent interface of Collection: Iterable Interface

A class that implements the Iterable can be used with the new for-loop.

The Iterable interface has only one method:

public interface Iterable<T> {
public Iterator<T> iterator();
}

It is possible to use your own collection type classes with the new for-loop. To do so, your class must implement thejava.lang.Iterable<E> interface. Here is a very basic example:

public class MyCollection<E> implements Iterable<E>{

    public Iterator<E> iterator() {
return new MyIterator<E>();
}
}

And here is the corresponding implementation skeleton of the MyIterator class:

public class MyIterator <T> implements Iterator<T> {

    public boolean hasNext() {

        //implement...
} public T next() {
//implement...;
} public void remove() {
//implement... if supported.
}
} 迭代器应用:
 list l = new ArrayList();
 l.add("aa");
 l.add("bb");
 l.add("cc");
 for (Iterator iter = l.iterator(); iter.hasNext();) {
  String str = (String)iter.next();
  System.out.println(str);
 }

Java sockets

A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes--Socket and ServerSocket--that implement the client side of the connection and the server side of the connection, respectively.

总: Client[port] <----->Server[listening port, communication port] ,

Server side: ServerSocket serverSocket = new ServerSocket(5000);  //Server will be listening to requests from clients on port 5000

Client side: Socket chatSocket = new Socket("192.1.168.100", 5000);  //The server is running on port 5000 at 192.1.168.100

Socket sock = serverSocket.accept();  //Server will return a new port to communicate with clients

InputStreamReader reader = new InputStreamReader(chatSocket.getInputStream());

BufferedReader breader = new BufferedReader(reader);

String msg = breader.readLine();

Reflection

1, Get Class: 如果compile time已知class,那可以A.class。如果runtime才知class name,那可以Class.forName("className");

Get Class以后就可以获取这个Class的所有信息,例如.getMethods(), .getConstructors(), .getInterfaces(), .getFields(), .getAnnotations()...

2, Get constructor以后可以Instantiate object:

Constructor constructor=A.class.getConstructor(String.class);

A a= (A) constructor.newInstance("StringArgument");

3, Get fields以后可以get 或set object里的这个field:

Field someField = A.class.getField("FieldName");  //.getField()方法只能获取public fields

A a = new A();

Object value = someField.get(a);

someField.set(a, value);

4,Get method以后可以invoke这个method on some object:

Method method = A.class.getMethod("MethodName", String.class);  //.getMethod()方法只能获取public methods

Object returnValue = method.invoke(new A(), "StringArgument");

5, Get private field/method

Field privateField = A.class.getDeclaredField("FieldName");  //or .getDeclaredMethod("MethodName");

privateField.setAccessible(true);

Object fieldValue = privateField.get(new A());

6, Get annotations

Annotations可以是在class上,或者method, field, parameter上...

在定义自己的@interface的时候,如果@Retention(RetentionPolicy.RUNTIME)表示在runtime时可以获取这个annotation.

Annotation annotation = A.class.getAnnotation(MyAnnotation.class);

if(annotation instanceof MyAnnotation) {annotation.getName();...}

Proxy

To create dynamic implementations of interface at runtime with the help of reflection.

InvocationHandler handler = new MyInvocationHandler(); //implement .invoke()方法

MyInterface proxy = (MyInterface) Proxy.newProxyInstance(MyInterface.class.getClassLoader(), new Class[] {MyInterface.class}, handler);

links

http://tutorials.jenkov.com/java-concurrency/blocking-queues.html

http://www.slideshare.net/JAX_London/java-core-understanding-the-disruptor-a-beginners-guide-to-hardcore-concurrency-trisha-gee-mike-barker

http://facultyfp.salisbury.edu/despickler/personal/Resources/AdvancedDataStructures/Handouts/AVL_TREES.pdf

https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#ie=UTF-8&q=CAS%20operations&sourceid=chrome-psyapi2

http://docs.oracle.com/javase/tutorial/essential/io/file.html

http://stackoverflow.com/questions/19966662/java-memory-model-and-final-fields

Factory design pattern

简单工厂模式就是客户选择一个工厂来生产不同区域的产品,The Simple Factory isn’t actually a Design Pattern; it’s more of a programming idiom.

由一个工厂来生产不同区域的产品,当区域太多时逻辑就变很多,所以工厂方法模式就是出现多个工厂来生产对应区域的不同类型的产品,所以这里有抽象工厂和具体工厂的分别。

例子:(Abstract class)PizzaStore-->(Sub classes)ItalyPizzaStore, SpainPizzaStore, SwedenPizzaStore...

defined orderPizza() method                    defined different details of createPizza() method to make ItalianStylePizza...

The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Examples:java.util.ResourceBundle#getBundle(), java.util.Calendar#getInstance().

对于抽象工厂,Abstract factory记住,Product interface->Product1, Product2..., Factory Interface->Factory1, Factory2, ...These factories will produces different combinations of products, so the abstract factory will return you the correct Factory# to use.

抽象工厂的区别是这里不只有一种产品(前面的pizza),还有薯条,比如具体工厂A生产芝士皮萨配细薯条, 工厂B生产西兰花皮萨配粗薯条。所以产品方面会有多个:抽象产品Pizza&Fries,具体产品CheesePizza_BroccoliPizza & ..。

An Abstract Factory gives us an interface for creating a family of products. By writing code that uses this interface, we decouple our code from the actual factory that creates the products. That allows us to implement a variety of factories that produce products meant for different contexts—such as different regions, different operating systems, or different look and feels.

This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.

多个抽象产品,多个抽象factory,一个factory producer class。

  • javax.xml.parsers.DocumentBuilderFactory#newInstance()

  • javax.xml.transform.TransformerFactory#newInstance()

  • javax.xml.xpath.XPathFactory#newInstance()

Advantage:

  • Factory methods eliminate the need to bind application-specific classes into your code.
  • The code only deals with the product interfaces; therefore, it can work with any user-defined concrete product classes.
  • Factory methods provide hooks for sub-classes to create different concrete products. In the example below, the Factory method MakeUISpecificCtrls provides the hook for creating the UI component specific controls. In the default CUIComponent, a simple edit control is created; however, we can change this behavior in the derived class to create an edit control which accepts only floating point values.
  • Factory methods connect parallel class hierarchies in such a way that it localizes the knowledge of which classes belong together. In the example below, the CUIComponent and CEditCtrl class hierarchies can be connected with each other. Also notice how the Factory method defines the connection between the two class hierarchies.

Disadvantage:

  • A potential disadvantage of Factory methods is that clients might have to sub-class the creator class just to create a particular concrete product object.
  • Subclassing is fine when the client has to subclass the creator class anyway, but otherwise, the client now must deal with another point of evolution.
  • In Factory Method pattern, the factory used for creating the objects is bound with the client code, i.e., it is difficult to use a different factory for creating objects.

Java runtime exception & checked exception

Runtime: NullPointerException, IndexOutOfBoundException, ArithmeticException(除0), ClassCastException, IllegalArgumentException.

CheckedException: 除了以上的这几个runtime的,其余都是checked,例如IOException, ClassNotFoundException, SQLException...

Clone() method:

When the clone method is invoked upon an array, it returns a reference to a new array which contains (or references) the same elements as the source array.

  int[] a = {1,2,3};
int[] b = a.clone();
System.out.println(a == b ? "Same Instance":"Different Instance");
//Outputs different instance

If were to modify int[] b the changes would not be reflected on int[] a since the two are separate object instances. This becomes slightly more complicated when the source array contains objects. The clone method will return a reference to a new array, which references the same objects as the source array.

  Dog[] myDogs = new Dog[2];
myDogs[0] = new Dog("Wolf");
myDogs[1] = new Dog("Pepper");
Dog[] myDogsClone = myDogs.clone();
System.out.println(myDogs[0] == myDogsClone[0] ? "Same":"Different"); //same
myDogsClone[0].setName("Ruff"); System.out.println(myDogs[0].getName()); //Outputs Ruff, However, changes to the array itself will only affect that array.

所以对于只包含primitive type的array, clone()就直接返回一个新的object,里面的内容和原object没关系。但如果原array里包含的是Object, 那么新的array Object里包含的是指向同一些objects的reference, 所以对新array里elements做修改会影响原array的Object。

  

[Java Basics2] Iterable, Socket, Reflection, Proxy, Factory DP的更多相关文章

  1. HibernateProxy异常处理 java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?

    这里使用google的Gson包做JSON转换,因为较早的1.4版本的FieldAttributes类中没有getDeclaringClass()这个方法,这个方法是获取field所属的类,在我的排除 ...

  2. Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?

    当我们使用gson 转对象时,并且这个对象中有一些属性是懒加载时如 @Entity @Table(name = "user") public class User { @Id @C ...

  3. Java设计模式之工厂模式(Factory模式)介绍(转载)

    原文见:http://www.jb51.net/article/62068.htm 这篇文章主要介绍了Java设计模式之工厂模式(Factory模式)介绍,本文讲解了为何使用工厂模式.工厂方法.抽象工 ...

  4. java.lang.NoClassDefFoundError: javassist/util/proxy/MethodFilter

    转自:https://blog.csdn.net/rchm8519/article/details/23788053 1. ERROR - Context initialization failedo ...

  5. Java中的Socket的用法

                                   Java中的Socket的用法 Java中的Socket分为普通的Socket和NioSocket. 普通Socket的用法 Java中的 ...

  6. Java-Spring:java.lang.ClassCastException: com.sun.proxy.$Proxy* cannot be cast to***问题解决方案

    java.lang.ClassCastException: com.sun.proxy.$Proxy* cannot be cast to***问题解决方案 临床表现: 病例: 定义代理类: @Tra ...

  7. java.lang.ClassCastException: com.sun.proxy.$Proxy32 cannot be cast to com.bkc.bpmp.core.cache.MemcachedManager

    java.lang.ClassCastException: com.sun.proxy.$Proxy32 cannot be cast to com.bkc.bpmp.core.cache.Memca ...

  8. Java反射机制(Reflection)

    Java反射机制(Reflection) 一.反射机制是什么 Java反射机制是程序在运行过程中,对于任意一个类都能够知道这个类的所有属性和方法;对于任意一个对象都能够调用它的任意一个方法和属性,这种 ...

  9. java网络编程socket解析

    转载:http://www.blogjava.net/landon/archive/2013/07/02/401137.html Java网络编程精解笔记2:Socket详解 Socket用法详解 在 ...

随机推荐

  1. 第十二天 jni 了解

    1 .什么是jni    java native interface  是一种协议. 用于java 和C 语言之间进行 通讯. 2. java  8中基本类型 . byte (1个字节)  short ...

  2. 【转载】详解CreateProcess调用内核创建进程的过程

    原文:详解CreateProcess调用内核创建进程的过程 昨天同学接到了腾讯的电面,有一题问到了CreateProcess创建进程的具体实现过程,他答得不怎么好吧应该是, 为了以防万一,也为了深入学 ...

  3. SQL疑难杂症【4 】大量数据查询的时候避免子查询

    前几天发现系统变得很慢,在Profiler里面发现有的SQL执行了几十秒才返回结果,当时的SQL如下: 可以看得出来,在652行用了子查询,恰巧目标表(QS_WIP)中的记录数为100000000+, ...

  4. UITableViewCell的cell重用原理

    iOS设备的内存有限,如果用UITableView显示成千上万条数据, 就需要成千上万个UITableViewCell对象的话, 那将会耗尽iOS设备的内存.要解决该问题,需要重用UITableVie ...

  5. Hibernate <二级缓存>

    二级缓存: 定义: 1.二级缓存被称为进程级缓存或者sessionFactory级缓存,二级缓存可以被所有session共享 2.二级缓存的生命周期和sessionFactory生命周期一样(sess ...

  6. vs2010 vc++ 统一修改所有工程的目录配置

    vs2005和vs2008中都是通过 工具-选项-项目和解决方案-VC++目录,设置 头文件include .库文件lib.可执行文件dll的路径,以便在引用dll动态链接库文件时,可以查找到该文件的 ...

  7. Deep Learning 12_深度学习UFLDL教程:Sparse Coding_exercise(斯坦福大学深度学习教程)

    前言 理论知识:UFLDL教程.Deep learning:二十六(Sparse coding简单理解).Deep learning:二十七(Sparse coding中关于矩阵的范数求导).Deep ...

  8. 如何管理linux开机自启服务

    如何管理linux开机自启服务? 自启动服务非常重要,例如 (1)需要手动添加希望自启的服务,如安装svn后没有自动添加,就需要我们手动加入(2)安装某些程序后,自动加到自启动了,但我们不需要,需要手 ...

  9. 【必备】史上最全的浏览器 CSS & JS Hack 手册(转)

    浏览器渲染页面的方式各不相同,甚至同一浏览器的不同版本(“杰出代表”是 IE)也有差异.因此,浏览器兼容成为前端开发人员的必备技能.如果有一份浏览器 Hack 手册,那查询起来就方便多了.这篇文章就向 ...

  10. 解决 LINUX mysql不能通过IP连接 只能localhost 权限没问题情况下

    最近朋友的一个服务器出现了一个奇怪的问题,弄了两个星期没有解决,在哥坚持不懈的努力下,终于解决了问题.发出来给需要的朋友. 问题:php程序连接mysql只能使用localhost,不能使用127.0 ...