List<Integer> ids = new continental gtArrayList<Integer>();最近ja

拒绝访问 | www. | 百度云加速
请打开cookies.
此网站 (www.) 的管理员禁止了您的访问。原因是您的访问包含了非浏览器特征(3be9c889f29943b3-ua98).
重新安装浏览器,或使用别的浏览器一、多数据源问题
主要思路是把dataSource、sqlSesstionFactory、MapperScannerConfigurer在配置中区分开,各Mapper对应的包名、类名区分开
1 &?xml version="1.0" encoding="UTF-8"?&
2 &beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
default-autowire="byName"&
&bean id="dataSource1" class="org.h2.jdbcx.JdbcConnectionPool"
destroy-method="dispose"&
&constructor-arg&
&bean class="org.h2.jdbcx.JdbcDataSource"&
&property name="URL" value="jdbc:h2:r:/h2db/awbprint/a"/&
&property name="user" value="sa"/&
&property name="password" value="sa"/&
&/constructor-arg&
&bean id="dataSource2" class="org.h2.jdbcx.JdbcConnectionPool"
destroy-method="dispose"&
&constructor-arg&
&bean class="org.h2.jdbcx.JdbcDataSource"&
&property name="URL" value="jdbc:h2:r:/h2db/awbprint/b"/&
&property name="user" value="sa"/&
&property name="password" value="sa"/&
&/constructor-arg&
&bean id="sqlSessionFactory1" class="org.mybatis.spring.SqlSessionFactoryBean"&
&property name="dataSource" ref="dataSource1"/&
&property name="configLocation" value="classpath:mybatis-config.xml"&&/property&
&property name="typeAliasesPackage" value="awbprint.mybatis.entity"&&/property&
&property name="mapperLocations" value="classpath:mybatis/a/**/*.xml"&&/property&
&bean id="sqlSessionFactory2" class="org.mybatis.spring.SqlSessionFactoryBean"&
&property name="dataSource" ref="dataSource2"/&
&property name="configLocation" value="classpath:mybatis-config.xml"&&/property&
&property name="typeAliasesPackage" value="awbprint.mybatis.entity"&&/property&
&property name="mapperLocations" value="classpath:mybatis/b/**/*.xml"&&/property&
&bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"&
&property name="sqlSessionFactoryBeanName" value="sqlSessionFactory1"&&/property&
&property name="basePackage" value="awbprint.mybatis.mapper.a"/&
&bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"&
&property name="sqlSessionFactoryBeanName" value="sqlSessionFactory2"&&/property&
&property name="basePackage" value="awbprint.mybatis.mapper.b"/&
62 &/beans&
上面的配置,一个连h2的a数据库,一个连h2的b数据库,至于事务管理器,大家可参考这个思路,建二个,各管各的。
项目中mapper接口及映射文件均用包名区分开,如下图:
二、如何使用Map做为参数及动态条件生成
&resultMap id="BaseResultMap" type="awbprint.mybatis.entity.PrintLayout"&
&id column="D_RECID" property="recid" jdbcType="DECIMAL"/&
&result column="D_USER_NAME" property="userName" jdbcType="VARCHAR"/&
&result column="D_NAME" property="name" jdbcType="VARCHAR"/&
&result column="D_TYPE" property="type" jdbcType="VARCHAR"/&
&/resultMap&
&sql id="Base_Column_List"&
D_RECID, D_USER_NAME, D_NAME, D_TYPE, ...
&select id="select" resultMap="BaseResultMap"
parameterType="java.util.Map"&
&include refid="Base_Column_List"/&
from T_PRINT_LAYOUT
where D_USER_NAME = #{userName,jdbcType=VARCHAR} and D_TYPE = #{awbType,jdbcType=VARCHAR}
&if test="recId != null"&
and D_RECID = #{recId,jdbcType=DECIMAL}
&if test="ids != null"&
or D_RECID in
&foreach item="item" index="index" collection="ids"
open="(" separator="," close=")"&
&/foreach&
14-31演示了如何使用Map做为参数,动态传入查询条件,及List参数生成in(...)条件
java端代码示例:
PrintLayoutMapper mapper = context.getBean(PrintLayoutMapper.class);
Map&String, Object& map = new HashMap&String, Object&();
map.put("userName", "ADMIN");
map.put("awbType", "CARGOLABEL_MU");
map.put("recId", 1);
List&Integer& ids = new ArrayList&Integer&();
ids.add(0, 1);
ids.add(0, 2);
ids.add(0, 3);
map.put("ids", ids);
List&?& list = mapper.select(map);
其实PrintLayoutMapper接口的定义为:
1 public interface PrintLayoutMapper {
List&PrintLayout& select(Map&String, Object& map);
最终生成的SQL语句为:
1 select D_RECID, D_USER_NAME, D_NAME, D_TYPE, ... from T_PRINT_LAYOUT where D_USER_NAME = ? and D_TYPE = ? and D_RECID = ? or D_RECID in ( ? , ? , ? )
三、兼容不同的数据库
1 &insert id="insert"&
&selectKey keyProperty="id" resultType="int" order="BEFORE"&
&if test="_databaseId == 'oracle'"&
select seq_users.nextval from dual
&if test="_databaseId == 'db2'"&
select nextval for seq_users from sysibm.sysdummy1"
&/selectKey&
insert into users values (#{id}, #{name})
11 &/insert&
这是官方文档上的示例,演示了如何兼容oracle与db2这二种不同的数据库,来获取序列的下一个值
四、加强版的分支、选择判断
1 &select id="findActiveBlogLike"
resultType="Blog"&
SELECT * FROM BLOG WHERE state = &ACTIVE&
&when test="title != null"&
AND title like #{title}
&when test="author != null and author.name != null"&
AND author_name like #{author.name}
&otherwise&
AND featured = 1
&/otherwise&
15 &/select&
这也是官方文档上的示例,因为&if&...&/if&并没对应的&else&标签,所以要达到&if&...&else&...&/else& &/if&的效果,得借助&choose&、&when&、&otherwise&组合使用。
五、避免Where 空条件的尴尬
1 &select id="findActiveBlogLike" resultType="Blog"&
SELECT * FROM BLOG
&if test="state != null"&
state = #{state}
7 &/select&
如果state参数为空时,最终生成SQL语句为&
SELECT * FROM BLOG
执行会出错,当然,你可以在where 后加一个1=1,改成
1 &select id="findActiveBlogLike" resultType="Blog"&
SELECT * FROM BLOG
&if test="state != null"&
and state = #{state}
7 &/select&
但是这个做法不太&环保&(毕竟引入了一个垃圾条件),其实只要改成&where&...&/where&即可
1 &select id="findActiveBlogLike" resultType="Blog"&
SELECT * FROM BLOG
&if test="state != null"&
and state = #{state}
8 &/select&
六、$与#的区别
select * from T_PRINT_LAYOUT where
D_RECID = ${recId}
最后生成的SQL为:
1 select * from T_PRINT_LAYOUT where
D_RECID = 1
即:直接将参数值替换到了原来${recId}的位置,相当于硬拼SQL
select * from T_PRINT_LAYOUT where
D_RECID = #{recid,jdbcType=DECIMAL}
最后生成的SQL为:
1 select * from T_PRINT_LAYOUT where
D_RECID = ?
即:#{...}被识别为一个SQL参数
七、大量数据的批量insert
大量数据(条数&10000)做insert时,如果按常规方式,每条insert into table(...) values(...);来提交,速度巨慢。改善性能的思路是多条insert批量提交。
oracle环境中,有一种批量insert的小技巧,原理是 insert into ... select from ...,套在mybatis上,变形为:
1 INSERT INTO T_TEST
(ID, COL_A, COL_B)
SELECT SEQ_TEST.NEXTVAL, A.*
SELECT 'A1', 'B1' FROM DUAL
UNION ALL SELECT 'A2', 'B2' FROM DUAL
UNION ALL SELECT 'A3', 'B3' FROM DUAL
UNION ALL SELECT 'A4', 'B4' FROM DUAL
UNION ALL SELECT 'A5', 'B5' FROM DUAL
UNION ALL SELECT 'A6', 'B6' FROM DUAL
中间的部分非常有规律,可以用foreach标签生成,参考下面的片段:
1 &insert id="insertBatch2" parameterType="ctas.entity.SharkFlt"&
&selectKey keyProperty="recId" order="BEFORE" resultType="Long"&
select SEQ_CTAS_SHARK_FLT.nextval as recId from dual
&/selectKey&
insert into CTAS_SHARK_FLT (&include refid="Base_Column_List"/&) SELECT SEQ_TEST.NEXTVAL, A.*
&foreach collection="list" item="item" index="index" open="" close="" separator="union all"&
select #{item.awbType,jdbcType=VARCHAR}, #{item.awbPre,jdbcType=VARCHAR},... from dual
&/foreach&
即使这样,也不能直接run,oracle中一次执行的sql语句长度是有限制的,如果最后拼出来的sql字符串过长,会导致执行失败,所以java端还要做一个分段处理,参考下面的处理:
List&SharkFlt& data = new ArrayList&SharkFlt&();
for (TSharkFlt f : sharkFlts) {
data.add(getSharkFlt(f));
System.out.println(data.size());
long beginTime = System.currentTimeMillis();
System.out.println("开始插入...");
SqlSessionFactory sqlSessionFactory = ctx.getBean(SqlSessionFactory.class);
SqlSession session = null;
session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
int a = 2000;//每次提交2000条
int loop = (int) Math.ceil(data.size() / (double) a);
List&SharkFlt& tempList = new ArrayList&SharkFlt&(a);
int start,
for (int i = 0; i & i++) {
tempList.clear();
start = i *
stop = Math.min(i * a + a - 1, data.size() - 1);
System.out.println("range:" + start + " - " + stop);
for (int j = j &= j++) {
tempList.add(data.get(j));
session.insert("ctas.importer.writer.mybatis.mappper.SharkFltMapper.insertBatch2", tempList);
session.clearCache();
System.out.println("已经插入" + (stop + 1) + " 条");
} catch (Exception e) {
e.printStackTrace();
session.rollback();
} finally {
if (session != null) {
session.close();
long endTime = System.currentTimeMillis();
System.out.println("插入完成,耗时 " + (endTime - beginTime) + " 毫秒!");
13,27-29这几行是关键,这一段逻辑会经常使用,为了重用,可以封装一下:
* 批量提交数据
* @param sqlSessionFactory
* @param mybatisSQLId SQL语句在Mapper XML文件中的ID
* @param commitCountEveryTime 每次提交的记录数
* @param list 要提交的数据列表
* @param logger 日志记录器
private &T& void batchCommit(SqlSessionFactory sqlSessionFactory, String mybatisSQLId, int commitCountEveryTime, List&T& list, Logger logger) {
SqlSession session = null;
session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
int commitCount = (int) Math.ceil(list.size() / (double) commitCountEveryTime);
List&T& tempList = new ArrayList&T&(commitCountEveryTime);
int start,
Long startTime = System.currentTimeMillis();
for (int i = 0; i & commitC i++) {
tempList.clear();
start = i * commitCountEveryT
stop = Math.min(i * commitCountEveryTime + commitCountEveryTime - 1, list.size() - 1);
for (int j = j &= j++) {
tempList.add(list.get(j));
session.insert(mybatisSQLId, tempList);
session.clearCache();
Long endTime = System.currentTimeMillis();
logger.debug("batchCommit耗时:" + (endTime - startTime) + "毫秒");
} catch (Exception e) {
logger.error("batchCommit error!", e);
e.printStackTrace();
session.rollback();
} finally {
if (session != null) {
session.close();
对应的,如果是批量update,也是类似的思路,只不过要注意一点:oracle环境中,多条语句提交的sql语句为
  update xxx set xxx =
  update xxx set xxx =
用mytais拼的时候,参考下面的写法:
&update id="updateBatch" parameterType="java.util.List"&
&foreach collection="list" item="item" index="index" open="begin" close="end;" &
update xxx set x=#{item.x,jdbcType=VARCHAR} where x =#{item.x,jdbcType=VARCHAR};
&/foreach&
关于批量提交的性能,Oracle环境下,我大概测试了一下:
insert into ... select xxx
& union all select yyy
最快,其次是
& insert into ... values &...;
& insert into ... values ...;
当然最慢是逐条insert提交,最后谈下Spring与mybatis集成后,AOP事务管理 对 批量提交的影响 ,通常情况下,我们会这样配置AOP事务管理:
&tx:advice id="txAdvice" transaction-manager="transactionManager"&
&tx:attributes&
&tx:method name="do*" read-only="false" rollback-for="java.lang.Exception"/&
&tx:method name="*" propagation="SUPPORTS" read-only="true"/&
&/tx:attributes&
&/tx:advice&
&aop:config&
&aop:pointcut id="pc" expression="execution(* ctas.service.*.*(..))"/&
&aop:advisor pointcut-ref="pc" advice-ref="txAdvice"/&
&/aop:config&
这样,ctas.service(及子包)下的所有方法都被拦截,而且只有do开头的方法,具有可写的事务(即:能insert/update/delete记录),而其它方法是只读事务(即:只能select数据),但是我们前面谈到的批量提交操作,都是写代码手动提交的,不需要spring管理,所以配置中需要将某些方法排除,可以约定self开头的方法,由开发者自己管理事务,不需要spring代为管理,上面的配置要改成:
&aop:config&
&aop:pointcut id="pc" expression="execution(* ctas.service.*.*(..)) and !execution(* ctas.service.*.self*(..)))"/&
&aop:advisor pointcut-ref="pc" advice-ref="txAdvice"/&
&/aop:config&
&通过 and !execution(...) 将self开头的方法排除就可以了,前面的批量操作代码写到selfXXX方法中。
关于批量提交,还有一种情况:父子表的批量插入。思路还是一样的,但是SQL的写法有点区别,原理参考下面的语句(Oracle环境)
DETAIL_ID INTEGER;
--第1组记录
SELECT SEQ_T_BASE.NEXTVAL INTO BASE_ID FROM DUAL;
INSERT INTO T_BASE (ID, FEE) VALUES (BASE_ID, ?);
SELECT SEQ_T_DETAIL.NEXTVAL INTO DETAIL_ID FROM DUAL;
INSERT INTO T_DETAIL (ID, BASE_ID, FEE) VALUES (DETAIL_ID, BASE_ID, ?);
SELECT SEQ_T_DETAIL.NEXTVAL INTO DETAIL_ID FROM DUAL;
INSERT INTO T_DETAIL (ID, BASE_ID, FEE) VALUES (DETAIL_ID, BASE_ID, ?);
--第2组记录
SELECT SEQ_T_BASE.NEXTVAL INTO BASE_ID FROM DUAL;
INSERT INTO T_BASE (ID, FEE) VALUES (BASE_ID, ?);
SELECT SEQ_T_DETAIL.NEXTVAL INTO DETAIL_ID FROM DUAL;
INSERT INTO T_DETAIL (ID, BASE_ID, FEE) VALUES (DETAIL_ID, BASE_ID, ?);
SELECT SEQ_T_DETAIL.NEXTVAL INTO DETAIL_ID FROM DUAL;
INSERT INTO T_DETAIL (ID, BASE_ID, FEE) VALUES (DETAIL_ID, BASE_ID, ?);
xml映射文件中的写法:
&insert id="insertBatch" parameterType="java.util.List"&
base_id INTEGER ;
detail_id INTEGER ;
&foreach collection="list" item="item" index="index" open="begin" close=""&
select seq_t_base.nextval into base_
insert into t_base(id, fee) values(base_id, #{item.baseEntity.fee,jdbcType=DECIMAL});
&foreach collection="item.details" item="detail" index="index"&
select seq_t_detail.nextval into detail_
insert into t_detail(id, base_id, fee) values(detail_id,base_id,#{detail.fee,jdbcType=DECIMAL});
&/foreach&
&/foreach&
&List中的Dto定义
1 public class BaseDetailDto {
private TBase baseE
private List&TDetail&
public TBase getBaseEntity() {
return baseE
public void setBaseEntity(TBase baseEntity) {
this.baseEntity = baseE
public List&TDetail& getDetails() {
public void setDetails(List&TDetail& details) {
this.details =
阅读(...) 评论()Post Reply
Bookmark Topic
Saloon Keepers:
Bartenders:
Difference between List&String& list1 = new ArrayList(); and List&String& list2 = new ArrayList&Stri
Naresh Shanmugam
Ranch Hand
(1) List&& list1 = new ArrayList();
(2) List&String& list2 = new ArrayList&String&();
With both of these options it allows us to add only String into the list.
Is there any other difference between those two??
Is it okey if i just use List&String& list1 = new ArrayList();
What is real significance of List&String& list2 = new ArrayList&String&();
than List&String& list1 = new ArrayList();
Garik Ustinov
Ranch Hand
Yes, it is allowed to do it this way in order to achieve backward compatibility with previous
And no, you don't want to code like this.
Consider the following:
List objList = new ArrayList();
objList.add(new Object());
List&String& list = objL
The compiler would be happy to compile this, but guess what you get in List&String&? An object!
By declaring a Collection&String&, you want to be sure that you get only Strings in there, while a raw type collections allow you to add anything. One day after refactoring your new ArrayList() will be returned from a separate method. Maybe the next day someone will add something to it and who knows, maybe this something won't be a String...
SCJP, SCWCD
Naresh Shanmugam
Ranch Hand
With List&String& list1 = new ArrayList();
(1) We cant add anything other than "String"
(2) List&Object& list2 = list1 will lead to COMPILER error
Similarly with List&String& list2 = new ArrayList&String&();
(1) We cant add anything other than "String"
(2) List&Object& list2 = list2 will lead to COMPILER error
Then what is the difference between those two..
List&String& list1 = new ArrayList();
and List&String& list2 = new ArrayList&String&();
Can any one give explanation please
I am confused !!!
Garik please let your view about this...
Ernest Friedman-Hill
author and iconoclast
Posts: 24217
Honestly, there is no real difference, but the only reason the second version is allowed is to make it easier to compile code that uses generics with old code that does not.
It's just better style to include the &String& in both places.
Ram Chhabra
Sorry, but what i understood from the discussion is that, the code:
List&String& list = new ArrayList()
will work fine in JDK 1.4... ???
Manjusha Muraleedas
Ranch Hand
As of my knowledge,
List&String& list1 = new ArrayList();
will throw a compile time "Warning".
if you use the following ... it wont give the warning... List&String& list1 = new ArrayList&String&();
in boh cases compiler restrinct addition of objects other than those of 'String ' wll give a compilation error.
(I don't know whether any other tricky things hided behind this.mixing of generics to legecy code has always been tricky for me)
Naresh Shanmugam
Ranch Hand
Thanks Ernest.. I got the point now..
kishan Jaiswal
List&String& lst=new ArrayList()
difference with
List&String& lst=new ArrayList&String&()
How JVM internally handle this two.
Why generic are called compile time ?
Jesper de Jong
Java Cowboy
Posts: 16043
Hello Kishan, welcome to the Ranch.
ArrayList without the generics is called a raw type. Raw types exist in Java only because of backward compatibility. When a new version of Java comes out, Oracle is always extremely careful to make sure that code written for the previous version still works without changes on the new version.
In Java 5, generics were added to Java. But there was at that point already a lot of code written without generics, and it was very important that this continued to work. So it is still possible to write code without using generics.
not do this, however, when you write new code. It is only necessary for backward compatibility.
kishan Jaiswal wrote:Why generic are called compile time ?
When the Java compiler translates your source code to byte code, it uses the generics in your code to check if you didn't make any mistakes with the types (for example, putting the wrong kind of object in a List&String&). But the generics are not translated into byte code - the byte code that is produced contains no information about the generics that you used.
So, generics are only important at compile time (when the compiler is translating your code) and not at runtime (when the JVM is running your program).
kishan Jaiswal wrote:How JVM internally handle this two.
Therefore, there is no difference between these two at the JVM level - the byte code for both of these two lines is the same.
Note that since Java 7 you can write this:
List&String& lst = new ArrayList&&();
Notice the && on the right side. This is shortcut syntax, so that you don't have to repeat the &String& that you already wrote on the left side. So, this syntax is exactly the same as:
List&String& lst = new ArrayList&String&();
but just with a little shorter syntax.
kishan Jaiswal
List&String& lst =new ArrayList(String);
lst.add("Fruit");
lst.add("Cosmetic");
System.out.println(lst.get(0)); //how jvm know whether he has to get the string or any other type if the generic information get removed in bytecode
Campbell Ritchie
Posts: 56146
kishan Jaiswal wrote:. . . how jvm know whether he has to get the string or any other type if the generic information get removed in bytecode
I moved that question out of the code tags in yuor post as the line would otherwise be .
Now, let&s look at the bytecode, which you can do with javap:-$ javac RawTypeDemo.java
Note: RawTypeDemo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
$ javap -c RawTypeDemo
Compiled from "RawTypeDemo.java"
class RawTypeDemo {
& RawTypeDemo();
&&&&&& 0: aload_0
&&&&&& 1: invokespecial #1&&&&&&&&&&&&&&&&& // Method java/lang/Object."&init&":()V
&&&&&& 4: return
& public void foo();
&&&&&& 0: new&&&&&&&&&& #2&&&&&&&&&&&&&&&&& // class java/util/ArrayList
&&&&&& 3: dup
&&&&&& 4: invokespecial #3&&&&&&&&&&&&&&&&& // Method java/util/ArrayList."&init&":()V
&&&&&& 7: astore_1
&&&&&& 8: aload_1
&&&&&& 9: ldc&&&&&&&&&& #4&&&&&&&&&&&&&&&&& // String Fruit
&&&&& 11: invokeinterface #5,& 2&&&&&&&&&&& // InterfaceMethod java/util/List.add:(Ljava/lang/O)Z
&&&&& 16: pop
&&&&& 17: aload_1
&&&&& 18: ldc&&&&&&&&&& #6&&&&&&&&&&&&&&&&& // String Cosmetic
&&&&& 20: invokeinterface #5,& 2&&&&&&&&&&& // InterfaceMethod java/util/List.add:(Ljava/lang/O)Z
&&&&& 25: pop
&&&&& 26: getstatic&&&& #7&&&&&&&&&&&&&&&&& // Field java/lang/System.out:Ljava/io/PrintS
&&&&& 29: aload_1
&&&&& 30: iconst_0
&&&&& 31: invokeinterface #8,& 2&&&&&&&&&&& // InterfaceMethod java/util/List.get:(I)Ljava/lang/O
&&&&& 36: checkcast&&&& #9&&&&&&&&&&&&&&&&& // class java/lang/String
&&&&& 39: invokevirtual #10&&&&&&&&&&&&&&&& // Method java/io/PrintStream.println:(Ljava/lang/S)V
&&&&& 42: return
$Note the raw type is shown as unsafe. Note the line starting 36: shows you are implicitly casting the contents to String. That is what happens when you have a List&String&: all its elements are implicitly cast to Strings, and that is how generics is implemented in the background. There is no record in the Class&RawTypeDemo& object of String anywhere, but the bytecode contains lines representing a cast to (String) on the List&s elements. That was using code very similar to what you posted.
Campbell Ritchie
Posts: 56146
import java.util.L
import java.util.ArrayL
class RawTypeDemo
&&& private void foo(String[] args)
&&&&&&& List&String& words = new ArrayList();
&&&&&&& for (String s : args)
&&&&&&&&&&& words.add(s);
&&&&&&& System.out.println(words);
&&&&&&& List numbers =
&&&&&&& numbers.add(Integer.valueOf(123));
&&&&&&& System.out.println(words.get(words.size() - 1));
&&& private RawTypeDemo()
&&&&&&& super();
&&& public static void main(String... args)
&&&&&&& new RawTypeDemo().foo(args);
}Now, you can assign your raw type to a plain simple List reference (line&14) and now you can add any type of Object to it. T you will get lots of compiler warnings especially if you write
javac -Xlint:unchecked RawTypeDemo.java
to get more details. Run this code with
java RawTypeDemo Kishan Jesper Campbell
or similar. I shall leave you to guess what will happen when you run line&16. I shall also leave you to explain why line 13 didn&t produce a printout on one of the occasions when I ran such code.
kishan Jaiswal
I execute the given code that you provide Campbell Ritchie and what I found is line 13 will simply print the words (of String type list) in a sop statement
and I understood that line 16 will definitely& produce an error because integer cant not be cast into the string.
Campbell Ritchie
Posts: 56146
Actually line&13 prints the List using its toString method, and it would be better to say that line&16 causes an exception to be thrown.
The problem with the raw type here is that it can be assigned to the wrong sort of reference and goodbye type‑safety.
Campbell Ritchie
Posts: 56146
The printing to System.out in line&13 and the exception message to System.err in line&16 may be printed by separate threads, and those threads may run at different speeds. If there is a delay in reaching System.out, the exception may be printed and the “main” th&read terminated before the System.out.println call is completed. So on one occasion I only saw the exception message, not the contents of the List.
Post Reply
Bookmark Topic
Boost this thread!
Similar Threads}

我要回帖

更多关于 gt 2000 new york 5 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信