`

Type safe,what would yout need a Collections.checkSet?

    博客分类:
  • Java
阅读更多
In one of the first posts on this blog I have discussed the problem of type checking (or lack of it) in some of Java collections even when using generics. Today I want to show you a similar issue that can break the type safety in your code. It’s a problem that can cause a really nasty bugs in your application – the ones that manifest themselves many thousand lines of code after the faulty method introduce it.

Imagine that you work with generics, but you use a third party code. What if some part of that code was written in Java 1.4 or earlier, therefore not using generics. Let’s go one step further: what if (for some reason) this code does not respect the typing of your collections? You would expect to get an error, right? Well, you’ll get one… but do you know when? Check the following code:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

	

public static void main(String[] args) {
    // create a type-safe set of Integers and add some values to it
    Set<Integer> setOfInts = new HashSet<Integer>();
    setOfInts.add(new Integer(7));
    setOfInts.add(new Integer(13));

    // pass your set to a non-generic code
    Set uncheckedSet = setOfInts;
    // non-generic code does not respect your typing
    // and adds a String to your set of integers
    uncheckedSet.add(new String("Illegal"));

    // back in your code - do some set manipulations:
    System.out.println(setOfInts);
    setOfInts.remove(new Integer(7));

    // at the end iterate trough your set
    for (Integer integer : setOfInts) {
        System.out.println(integer);
    }
}

The code above is a simplified version of the described scenario. In lines 8 – 11 the ‘third party’ code is executed and adds a String into a set of Integers. So back to the question: in a given example when will error occur? One might assume in line 11 as the bad element is inserted… wrong! Maybe when we access the collection and print all of its elements?… wrong! We can even do some manipulations on it (line 15) and still be fine! The error will show his ugly head finally in the loop in line 18 when we will enter it for the second time. This will happen so late because in line 18 for the first time we access the inserted String and cast it to Integer – at this point ClassCastException occurs.

In the example above the distance between the faulty insertion and the place where exception is thrown is only seven lines, but you can imagine its being 7000. Your code can be working fine for 7000 hours and after that throw an exception that will basically give you no hint what’s wrong. If you do not use third party code you should not feel safe because of that – I am sure that if your project has more than 10000 lines there is a part of it so old and dusty that it was written without the usage of generics…

What can be done? Well, we are in luck as there is a quite simple way of protecting yourself from that: in java.util.Collections you will find a way to wrap your Set, Map or List into an forwarding class that will check in runtime the typing of the inserted objects. In the case of our code snippet we only need to add one line:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:

	

public static void main(String[] args) {
    // create a type-safe set of Integers and add some values to it
    Set<Integer> setOfInts = new HashSe<Integer>();
    setOfInts = Collections.checkedSet(setOfInts, Integer.class);
    setOfInts.add(new Integer(7));
    setOfInts.add(new Integer(13));

    // pass your set to a non-generic code
    Set uncheckedSet = setOfInts;
    // non-generic code does not respect your typing
    // and adds a String to your set of integers
    uncheckedSet.add(new String("Illegal"));

    // back in your code - do some set manipulations:
    System.out.println(setOfInts);
    setOfInts.remove(new Integer(7));

    // at the end iterate trough your set
    for (Integer integer : setOfInts) {
        System.out.println(integer);
    }
}

As you see the only difference between this and previous snippet is additional line (#4) in which we wrap our set of integers into a CheckedSet. See that due to Generic type erasure in Java the Collections.checked* methods require a class object besides a collection to wrap. Now when we run the new code the error will manifest itself just at the moment where an error is commited: in line 12 when we try to insert a string. Exactly what we needed!

To summarize: if in your project you use either third party code or legacy code that you suspect of not using generics consider wrapping your collections with Collection.checked* methods!

分享到:
评论

相关推荐

    yout_download_final.rar

    我没试过,我想会是好东西,在国外找的;希望有人来下载哦,呵呵

    pypxl:pxlapi的异步包装器

    px 的异步包装器安装它只需使用pip3 install pypxl进行安装如何使用它from pypxl import Pxlapi#Define yout details herepxl = Pxlapi ( token = "Your pxlapi token" , stop_on_error = False ) 现在,仅需一行...

    Android代码-Sorters

    If yout would help this project, fell free to join. For now i just implement 3 diferent sorters but I wish to implement more in the future. The sorters implemented are: Bubble Selection Insertion ...

    Android代码-Migratron

    Android port of MTMigration for Android to execute pieces of code that only need to run once on version updates. This could be anything from data normalization routines, "What's New In This Version" ...

    snr_SNDR_newsdhy_matlab_TheFirst_ENOB_

    SNR/SNDR/THD/ENOB will be provided.% Input frequency(fin) is calculated automaticly by this program.% yout fsample fb are must.% input matrix must be Nx1 or 1xN. If it is MxN first row will be used.%...

    verilog_cordic_core_latest.tar.gz_library verilog_verilog librar

    ` 定义名为`cordic_core`的Verilog模块,接受输入向量`Xin`和`Yin`,以及时钟`clk`,并提供输出向量`Xout`和`Yout`。 2. **参数声明**:`parameter WIDTH = n, STAGES = m;` 声明算法的位宽`WIDTH`和迭代阶段数`...

    Android代码-MultiTypeAdapter

    全面、支持 bean type 之间 一对一 和 一对多 的关系绑定 职责单一、只负责本分工作,专注多类型的列表视图 类型分发,不会影响 view 的内容或行为 内存、没有性能损失,内存友好 可读、代码清晰干净 基础用法 ...

    组态王Pid控件使用方法.doc

    2. 属性类型关联对象:包括 SP、PV、YOUT、Type、CtrlPeriod、FeedbackFilter、FillterTime、CtrlLimitHigh、CtrlLimitLow、InputHigh、InputLow、OutputHigh、OutputLow、Kp、Ti、Td、Tf、ReverseEffect、...

    单神经元自适应pid控制

    ### 单神经元自适应PID控制器 #### 一、引言 在自动化控制领域,PID(比例-积分-微分)控制器是一种广泛应用的反馈控制机制,用于维持系统输出与期望值之间的误差最小化。传统的PID控制器参数(比例增益\(K_p\)、...

    16位乘法器芯片verilog设计实验Quartus9.1工程源码+设计说明文件.zip

    if(areg[i-1]) yout_r = {1'b0,yout[30:15]+breg,yout_r[14:1]}; //累加并移位 else yout_r &lt;= yout_r&gt;&gt;1; //移位不累加 end else if(i == 5'd16 && areg[15]) yout_r[31:16] &lt;= yout_r[31:...

    C语言PTA平台习题与答案PDF

    Wielcome lo Yout 0include&lt;stdia.h&gt; int main() printf(Welcome to You!n"); retur 0; ②-本题要求编写程序,计算字或温度100°时保的须氏温度。计算公式: C*S&gt;(F-32y9式中。表示搞氏漏度。F表示平氏温度,输出数剂...

    滤波器设计.v

    module dec fit clk4x hsin vsin rin gin bin cntrl yout p uout p vout p yout n uout n vout n hsout vsout tout clk2x clk1x ; input clk4x clk2x clk1x; input [7:0] rin gin bin; input hsin vsin; input ...

    基于Arduino:球轮机器人(完整程序+3D建模文件).zip

    With a rotation of less than this value, * the robot will stand still */ double deadzone = 1.5; /* Buffers for timing, gyro data and PID outputs */ long lastMillis; double xAngle, yAngle; double x...

    组态王Pid控件使用方法.pdf

    * 属性类型关联对象:包括SP、PV、YOUT、Type、CtrlPeriod、FeedbackFilter、FillterTime、CtrlLimitHigh、CtrlLimitLow、InputHigh、InputLow、OutputHigh、OutputLow、Kp、Ti、Td、Tf、ReverseEffect、...

    django-demirbank:用于 demirbank 支付的 Django 库

    'Auth'DEMIR_BANK_INSTALMENT = ''DEMIR_BANK_OK_URL = 'http://to.yout.site/path/to/pay/success'DEMIR_BANK_FAIL_URL = 'http://to.yout.site/path/to/pay/fail'DEMIR_BANK_STORE_TYPE = '3d_Pay_Hosting'

    FNN類神經網路

    - `New_Wi = Wi + Lw * (A*em_1 + em_2) * Yout3_i` - 其中,`Lw`为学习率;`A*em_1 + em_2`可以视为损失函数的导数(梯度);`Yout3_i`为第三层节点的输出。 ### 总结 这段代码展示了一个简单的FNN实现,包括了...

    组态王Pid控件使用方法.docx

    - **属性设置**:关联SP、PV、YOUT等变量,配置PID类型、控制周期、滤波器设置以及限幅值等。 4. **命令语言使用**: - **变量关联**:只有当控件所在画面处于激活状态时,控制功能才会执行。在画面命令语言中,...

    EDA如何看图写程序 复习

    5. 最后一个例子中的`YOUT`被声明为`buffer`类型,这意味着它不仅是一个信号,还作为输出的缓冲器,其值会立即反映输入`YOUT`的变化。`YOUT`的更新取决于`CLK`和`B`,这可能会引入反馈,需要特别注意时序和稳定性...

Global site tag (gtag.js) - Google Analytics