1.写一个Singleton出来。
Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。
一般Singleton模式通常有几种种形式:
第一种形式: 定义一个类,它的构造函数为private的,它有一个static的private的该类变量,在类初始化时实例话,通过一个public的getInstance方法获取对它的引用,继而调用其中的方法。
public class Singleton {
private Singleton(){}
//在自己内部定义自己一个实例,是不是很奇怪?
//注意这是private 只供内部调用
private static Singleton instance = newSingleton();
//这里提供了一个供外部访问本class的静态方法,可以直接访问
public static Singleton getInstance() {
return instance;
}
}
第二种形式:
public class Singleton {
private static Singletoninstance = null;
public staticsynchronized Singleton getInstance() {
//这个方法比上面有所改进,不用每次都进行生成对象,只是第一次
//使用时生成实例,提高了效率!
if (instance==null)
instance=new Singleton();
return instance;
}
}
其他形式:
定义一个类,它的构造函数为private的,所有方法为static的。
一般认为第一种形式要更加安全些
2、排序都有哪几种方法?请列举。用JAVA实现一个快速排序。
3、有数组a[n],用java代码将数组元素顺序颠倒
public class ReverseTest {public int[] reversArray(int[] array) {
int len = array.length;
int temp;
for(int i=0;i<len/2;i++) {
temp = array[i];
array[i] = array[len-i-1];
array[len-i-1] = temp;
}
return array;
}
public static void main(String[] args) {
//数组初始化必须给定初始的大小
int[] array = {1,2,3,4,5,6,7,8,9,10};
ReverseTest test = new ReverseTest();
int[] reversArray = test.reversArray(array);
for(int num: reversArray) {
System.out.print(num+" ");
}
}
}
4、写一段代码连接数据库并进行操作
package jichu.test;import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class JdbcTest {
private Connection con = null;
private PreparedStatement preparedStatement = null;
public Connection getCon() throws SQLException {
con = (Connection) DriverManager.getConnection("jdbc:mysql:///test","root","tao");
return con;
}
public void doSomething() throws SQLException {
preparedStatement = (PreparedStatement) getCon().prepareStatement("select*from city where cityName = ?");
preparedStatement.setString(1, "上海");
ResultSet rs = preparedStatement.executeQuery();
while(rs.next()) {
System.out.println(rs.getInt(1)+rs.getString(2));
}
}
public void closeCon() {
if(preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws SQLException {
JdbcTest jt = new JdbcTest();
jt.doSomething();
jt.closeCon();
}
}